简体   繁体   English

分配的方法作为异步任务 <t> 在C#中

[英]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: 您好我有一个问题:分配为异步Task方法将自动创建一个新Task,然后将方法中的代码运行到刚刚创建的新任务中,例如,假设我在一个方法中有一个post方法webapi2像这样:

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 我将使用我的应用程序中的HttpClient将该方法称为awaitable。我应该使用

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. 要在post方法内部启动任务,还是在方法指定为Task时立即启动任务?我只是想更好地了解异步方法。 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? 我应该使用Task.Run在post方法内部启动任务,还是在方法指定为Task时立即启动任务?

In an async method, the async keyword controls creating the Task object for you. async方法中, async关键字控制为您创建Task对象。 You do not need to create another one. 您不需要创建另一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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