简体   繁体   中英

Assigned methods as async Task<t> in c#

Hello i have a question:An assigned as async Task method will automatically create a new Task and then will run the code inside the method into the new task that has just been created?For example lets just say that i have a post method in a webapi2 like this:

public async Task<IHttpActionResult> Post([FromBody]Menu m)
{
    using (MySqlConnection con = new MySqlConnection(""))
    using (MySqlCommand cmd = new MySqlCommand("Insert into Menu (Description,LanguageId,IsActive) values (@Description,@LanguageId,@IsActive) ", con))
    {
        try
        {
            if (con.State == ConnectionState.Closed)
            {
                await con.OpenAsync();
                cmd.Parameters.AddWithValue("@Description", m.Description);
                cmd.Parameters.AddWithValue("@LanguageId", m.LanguageId);
                cmd.Parameters.AddWithValue("@IsActive", m.IsActive);
                await cmd.ExecuteNonQueryAsync();
            }
        }
        catch (MySqlException ex)
        {
            return Content(HttpStatusCode.NotFound,ex);
        }
        finally
        {
           await  con.CloseAsync();
        }
        return Ok("Inserted Succesfully");
    }
}

i will call this method as awaitable using an HttpClient in my application.Should i use

Task.Run( () =>
{
    //database code
});

to start the task inside the post method or as soon as the method is assigned as Task will start the task automatically?I just want to understand better the asynchronous methods. Thanks!

Should i use Task.Run to start the task inside the post method or as soon as the method is assigned as Task will start the task automatically?

In an async method, the async keyword controls creating the Task object for you. You do not need to create another one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM