When trying to run Insert query in MySql using Task.Run(), it throws the follow exception: “Unable to...












0














Here is the code:



static void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e) //Event Handler
{
Time timeToSend = JsonConvert.DeserializeObject<Time>(Encoding.UTF8.GetString(e.Message));

Task.Run(async () => await SendToMySql(timeToSend));
}


In the SendToMySql method, it basically a insert, as follows:



private static async Task SendToMySql(Time timeToSend)
{
try
{
var connection = new MySqlConnection(string.Format(configuration["MySql:ConnectionString"], configuration["MySql:DataBaseName"]));
await connection.OpenAsync();
string query = "insert into resource_log (resource_value_log, creation_date) values ('" + timeToSend.Message + "',STR_TO_DATE( '" + DateTime.Now + "', '%d/%m/%Y %H:%i:%s'))";
var cmd = new MySqlCommand(query, connection);
await cmd.ExecuteReaderAsync();
await connection.CloseAsync();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}


I called this method using the Task.Run() cause i wanted it too run asynchronous if necessary. But it throws the following exception:




"Unable to connect to any of the specified MySQL hosts."




Here is the inner Exception:




Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.




Some of the data was actually inserted into the MySql.



I am new to asynchronous and parallel programming and I coded this way but I wonder if this is the right way to do a asynchronous query on MySql. I did it the same way as this, but with MongoDb, and it worked fine. Hope you guys can help me. Thanks.










share|improve this question
























  • Try ExecuteNonQuery instead of cmd.ExecuteReaderAsync. And I don't think you need to code like this. Just do normal Connection.Open. . . .Close Only run the method itself asynchronously.
    – T.S.
    Nov 11 at 18:55












  • You're not calling .Dispose() on your MysqlConnection and your MySqlCommand. This may or may not explain why it fails after a while
    – Kevin Gosse
    Nov 11 at 19:05










  • I changed to ExecuteNonQuery and to Open and Close, but it throws the same exception. It only works without throwing the exception if I do not use Task.Run(), but I want it to run parallel.
    – Gui Oliveira
    Nov 11 at 19:05






  • 1




    Also, your MySQL database has a limit of concurrent connections. If you start a lot of those tasks in parallel, some will have to wait for a connection to be freed, which could cause timeouts
    – Kevin Gosse
    Nov 11 at 19:08










  • I added the following code:
    – Gui Oliveira
    Nov 11 at 19:10
















0














Here is the code:



static void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e) //Event Handler
{
Time timeToSend = JsonConvert.DeserializeObject<Time>(Encoding.UTF8.GetString(e.Message));

Task.Run(async () => await SendToMySql(timeToSend));
}


In the SendToMySql method, it basically a insert, as follows:



private static async Task SendToMySql(Time timeToSend)
{
try
{
var connection = new MySqlConnection(string.Format(configuration["MySql:ConnectionString"], configuration["MySql:DataBaseName"]));
await connection.OpenAsync();
string query = "insert into resource_log (resource_value_log, creation_date) values ('" + timeToSend.Message + "',STR_TO_DATE( '" + DateTime.Now + "', '%d/%m/%Y %H:%i:%s'))";
var cmd = new MySqlCommand(query, connection);
await cmd.ExecuteReaderAsync();
await connection.CloseAsync();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}


I called this method using the Task.Run() cause i wanted it too run asynchronous if necessary. But it throws the following exception:




"Unable to connect to any of the specified MySQL hosts."




Here is the inner Exception:




Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.




Some of the data was actually inserted into the MySql.



I am new to asynchronous and parallel programming and I coded this way but I wonder if this is the right way to do a asynchronous query on MySql. I did it the same way as this, but with MongoDb, and it worked fine. Hope you guys can help me. Thanks.










share|improve this question
























  • Try ExecuteNonQuery instead of cmd.ExecuteReaderAsync. And I don't think you need to code like this. Just do normal Connection.Open. . . .Close Only run the method itself asynchronously.
    – T.S.
    Nov 11 at 18:55












  • You're not calling .Dispose() on your MysqlConnection and your MySqlCommand. This may or may not explain why it fails after a while
    – Kevin Gosse
    Nov 11 at 19:05










  • I changed to ExecuteNonQuery and to Open and Close, but it throws the same exception. It only works without throwing the exception if I do not use Task.Run(), but I want it to run parallel.
    – Gui Oliveira
    Nov 11 at 19:05






  • 1




    Also, your MySQL database has a limit of concurrent connections. If you start a lot of those tasks in parallel, some will have to wait for a connection to be freed, which could cause timeouts
    – Kevin Gosse
    Nov 11 at 19:08










  • I added the following code:
    – Gui Oliveira
    Nov 11 at 19:10














0












0








0







Here is the code:



static void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e) //Event Handler
{
Time timeToSend = JsonConvert.DeserializeObject<Time>(Encoding.UTF8.GetString(e.Message));

Task.Run(async () => await SendToMySql(timeToSend));
}


In the SendToMySql method, it basically a insert, as follows:



private static async Task SendToMySql(Time timeToSend)
{
try
{
var connection = new MySqlConnection(string.Format(configuration["MySql:ConnectionString"], configuration["MySql:DataBaseName"]));
await connection.OpenAsync();
string query = "insert into resource_log (resource_value_log, creation_date) values ('" + timeToSend.Message + "',STR_TO_DATE( '" + DateTime.Now + "', '%d/%m/%Y %H:%i:%s'))";
var cmd = new MySqlCommand(query, connection);
await cmd.ExecuteReaderAsync();
await connection.CloseAsync();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}


I called this method using the Task.Run() cause i wanted it too run asynchronous if necessary. But it throws the following exception:




"Unable to connect to any of the specified MySQL hosts."




Here is the inner Exception:




Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.




Some of the data was actually inserted into the MySql.



I am new to asynchronous and parallel programming and I coded this way but I wonder if this is the right way to do a asynchronous query on MySql. I did it the same way as this, but with MongoDb, and it worked fine. Hope you guys can help me. Thanks.










share|improve this question















Here is the code:



static void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e) //Event Handler
{
Time timeToSend = JsonConvert.DeserializeObject<Time>(Encoding.UTF8.GetString(e.Message));

Task.Run(async () => await SendToMySql(timeToSend));
}


In the SendToMySql method, it basically a insert, as follows:



private static async Task SendToMySql(Time timeToSend)
{
try
{
var connection = new MySqlConnection(string.Format(configuration["MySql:ConnectionString"], configuration["MySql:DataBaseName"]));
await connection.OpenAsync();
string query = "insert into resource_log (resource_value_log, creation_date) values ('" + timeToSend.Message + "',STR_TO_DATE( '" + DateTime.Now + "', '%d/%m/%Y %H:%i:%s'))";
var cmd = new MySqlCommand(query, connection);
await cmd.ExecuteReaderAsync();
await connection.CloseAsync();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}


I called this method using the Task.Run() cause i wanted it too run asynchronous if necessary. But it throws the following exception:




"Unable to connect to any of the specified MySQL hosts."




Here is the inner Exception:




Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.




Some of the data was actually inserted into the MySql.



I am new to asynchronous and parallel programming and I coded this way but I wonder if this is the right way to do a asynchronous query on MySql. I did it the same way as this, but with MongoDb, and it worked fine. Hope you guys can help me. Thanks.







c# mysql asynchronous parallel-processing async-await






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 11 at 18:57









T.S.

9,64593153




9,64593153










asked Nov 11 at 18:43









Gui Oliveira

152




152












  • Try ExecuteNonQuery instead of cmd.ExecuteReaderAsync. And I don't think you need to code like this. Just do normal Connection.Open. . . .Close Only run the method itself asynchronously.
    – T.S.
    Nov 11 at 18:55












  • You're not calling .Dispose() on your MysqlConnection and your MySqlCommand. This may or may not explain why it fails after a while
    – Kevin Gosse
    Nov 11 at 19:05










  • I changed to ExecuteNonQuery and to Open and Close, but it throws the same exception. It only works without throwing the exception if I do not use Task.Run(), but I want it to run parallel.
    – Gui Oliveira
    Nov 11 at 19:05






  • 1




    Also, your MySQL database has a limit of concurrent connections. If you start a lot of those tasks in parallel, some will have to wait for a connection to be freed, which could cause timeouts
    – Kevin Gosse
    Nov 11 at 19:08










  • I added the following code:
    – Gui Oliveira
    Nov 11 at 19:10


















  • Try ExecuteNonQuery instead of cmd.ExecuteReaderAsync. And I don't think you need to code like this. Just do normal Connection.Open. . . .Close Only run the method itself asynchronously.
    – T.S.
    Nov 11 at 18:55












  • You're not calling .Dispose() on your MysqlConnection and your MySqlCommand. This may or may not explain why it fails after a while
    – Kevin Gosse
    Nov 11 at 19:05










  • I changed to ExecuteNonQuery and to Open and Close, but it throws the same exception. It only works without throwing the exception if I do not use Task.Run(), but I want it to run parallel.
    – Gui Oliveira
    Nov 11 at 19:05






  • 1




    Also, your MySQL database has a limit of concurrent connections. If you start a lot of those tasks in parallel, some will have to wait for a connection to be freed, which could cause timeouts
    – Kevin Gosse
    Nov 11 at 19:08










  • I added the following code:
    – Gui Oliveira
    Nov 11 at 19:10
















Try ExecuteNonQuery instead of cmd.ExecuteReaderAsync. And I don't think you need to code like this. Just do normal Connection.Open. . . .Close Only run the method itself asynchronously.
– T.S.
Nov 11 at 18:55






Try ExecuteNonQuery instead of cmd.ExecuteReaderAsync. And I don't think you need to code like this. Just do normal Connection.Open. . . .Close Only run the method itself asynchronously.
– T.S.
Nov 11 at 18:55














You're not calling .Dispose() on your MysqlConnection and your MySqlCommand. This may or may not explain why it fails after a while
– Kevin Gosse
Nov 11 at 19:05




You're not calling .Dispose() on your MysqlConnection and your MySqlCommand. This may or may not explain why it fails after a while
– Kevin Gosse
Nov 11 at 19:05












I changed to ExecuteNonQuery and to Open and Close, but it throws the same exception. It only works without throwing the exception if I do not use Task.Run(), but I want it to run parallel.
– Gui Oliveira
Nov 11 at 19:05




I changed to ExecuteNonQuery and to Open and Close, but it throws the same exception. It only works without throwing the exception if I do not use Task.Run(), but I want it to run parallel.
– Gui Oliveira
Nov 11 at 19:05




1




1




Also, your MySQL database has a limit of concurrent connections. If you start a lot of those tasks in parallel, some will have to wait for a connection to be freed, which could cause timeouts
– Kevin Gosse
Nov 11 at 19:08




Also, your MySQL database has a limit of concurrent connections. If you start a lot of those tasks in parallel, some will have to wait for a connection to be freed, which could cause timeouts
– Kevin Gosse
Nov 11 at 19:08












I added the following code:
– Gui Oliveira
Nov 11 at 19:10




I added the following code:
– Gui Oliveira
Nov 11 at 19:10












1 Answer
1






active

oldest

votes


















0














It’s a longstanding bug in Connector/NET (MySql.Data) that none of the Async methods actually execute asynchronously: bug 70111.



To fix this, you can switch to an alternative ADO.NET MySQL library, which is 100% async: MySqlConnector on GitHub and NuGet.



Although MySqlConnector does implement a CloseAsync method, the default implementation synchronously returns the open connection to the connection pool, so I would recommend omitting the CloseAsync call and just using a using block to Dispose the connection when you're done with it:



using (var connection = new MySqlConnection(string.Format(configuration["MySql:ConnectionString"], configuration["MySql:DataBaseName"])))
{
await connection.OpenAsync();
var query = "...";
using (var cmd = new MySqlCommand(query, connection))
await cmd.ExecuteReaderAsync();
}





share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53251979%2fwhen-trying-to-run-insert-query-in-mysql-using-task-run-it-throws-the-follow%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    It’s a longstanding bug in Connector/NET (MySql.Data) that none of the Async methods actually execute asynchronously: bug 70111.



    To fix this, you can switch to an alternative ADO.NET MySQL library, which is 100% async: MySqlConnector on GitHub and NuGet.



    Although MySqlConnector does implement a CloseAsync method, the default implementation synchronously returns the open connection to the connection pool, so I would recommend omitting the CloseAsync call and just using a using block to Dispose the connection when you're done with it:



    using (var connection = new MySqlConnection(string.Format(configuration["MySql:ConnectionString"], configuration["MySql:DataBaseName"])))
    {
    await connection.OpenAsync();
    var query = "...";
    using (var cmd = new MySqlCommand(query, connection))
    await cmd.ExecuteReaderAsync();
    }





    share|improve this answer


























      0














      It’s a longstanding bug in Connector/NET (MySql.Data) that none of the Async methods actually execute asynchronously: bug 70111.



      To fix this, you can switch to an alternative ADO.NET MySQL library, which is 100% async: MySqlConnector on GitHub and NuGet.



      Although MySqlConnector does implement a CloseAsync method, the default implementation synchronously returns the open connection to the connection pool, so I would recommend omitting the CloseAsync call and just using a using block to Dispose the connection when you're done with it:



      using (var connection = new MySqlConnection(string.Format(configuration["MySql:ConnectionString"], configuration["MySql:DataBaseName"])))
      {
      await connection.OpenAsync();
      var query = "...";
      using (var cmd = new MySqlCommand(query, connection))
      await cmd.ExecuteReaderAsync();
      }





      share|improve this answer
























        0












        0








        0






        It’s a longstanding bug in Connector/NET (MySql.Data) that none of the Async methods actually execute asynchronously: bug 70111.



        To fix this, you can switch to an alternative ADO.NET MySQL library, which is 100% async: MySqlConnector on GitHub and NuGet.



        Although MySqlConnector does implement a CloseAsync method, the default implementation synchronously returns the open connection to the connection pool, so I would recommend omitting the CloseAsync call and just using a using block to Dispose the connection when you're done with it:



        using (var connection = new MySqlConnection(string.Format(configuration["MySql:ConnectionString"], configuration["MySql:DataBaseName"])))
        {
        await connection.OpenAsync();
        var query = "...";
        using (var cmd = new MySqlCommand(query, connection))
        await cmd.ExecuteReaderAsync();
        }





        share|improve this answer












        It’s a longstanding bug in Connector/NET (MySql.Data) that none of the Async methods actually execute asynchronously: bug 70111.



        To fix this, you can switch to an alternative ADO.NET MySQL library, which is 100% async: MySqlConnector on GitHub and NuGet.



        Although MySqlConnector does implement a CloseAsync method, the default implementation synchronously returns the open connection to the connection pool, so I would recommend omitting the CloseAsync call and just using a using block to Dispose the connection when you're done with it:



        using (var connection = new MySqlConnection(string.Format(configuration["MySql:ConnectionString"], configuration["MySql:DataBaseName"])))
        {
        await connection.OpenAsync();
        var query = "...";
        using (var cmd = new MySqlCommand(query, connection))
        await cmd.ExecuteReaderAsync();
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 12 at 3:03









        Bradley Grainger

        19.4k46486




        19.4k46486






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53251979%2fwhen-trying-to-run-insert-query-in-mysql-using-task-run-it-throws-the-follow%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown