在 c# 中,当我们在方法逻辑中使用 Task.Run() 来调用后台线程时,是否必须使用 async 关键字来调用方法?
In c# is it mandatory to use async keyword for calling method when we use Task.Run() inside the method logic to run the thread in the background?
下面是代码片段:
public async Task<ActionResult> GetProduct(int id)
{
/*
---- some main thread logic...
*/
Task.Run(() => {
/*
---- some background thread logic...
*/
});
return View();
}
在上面的代码中,我可以在 action 方法中不使用 async 关键字来调用 Task.Run() 逻辑吗?
Task.Run() 是否必须使用 async 关键字?
请帮我弄清楚。
不,这不是强制性的。
当您想在方法中使用 await
时,请使用 async
关键字。
下面是代码片段:
public async Task<ActionResult> GetProduct(int id)
{
/*
---- some main thread logic...
*/
Task.Run(() => {
/*
---- some background thread logic...
*/
});
return View();
}
在上面的代码中,我可以在 action 方法中不使用 async 关键字来调用 Task.Run() 逻辑吗? Task.Run() 是否必须使用 async 关键字?
请帮我弄清楚。
不,这不是强制性的。
当您想在方法中使用 await
时,请使用 async
关键字。