![](/img/trans.png)
[英]I have a thread.pool and how can i make Main Thread wait until all task are completed?
[英]How to wait main thread until async task is completed in C#
我有一个异步任务,需要比主线程更长的时间。 主线程在异步任务之前完成,例如,我看不到异步任务的结果,我看不到数据库记录应插入哪个异步任务。
这是我的代码
框架4.5
public void Load(int id)
{
Task asynctask1;
asynctask1 = CallWithAsync(id); // this is async task
task2(); // main thread
task3(); // main thread
}
private async static Task CallWithAsync(int id)
{
string result = "";
try
{
result = await InsertDataAsync(id);
}
catch (Exception ex)
{
//do some error logging
}
//return result;
}
static Task<string> InsertDataAsync(int id)
{
return Task.Run<string>(() =>
{
return InsertData(id);
});
}
static string InsertData(int id)
{
try
{
System.Threading.Thread.Sleep(5000);//we have some code here which takes longer
//code to insert DB record
}
catch (Exception ex)
{
//do some error logging
}
return "success";
}
public void task2()
{
//some thing
}
public void task3()
{
//some thing
}
等待方法结束时完成任务:
public void Load(int id)
{
Task asynctask1;
asynctask1 = CallWithAsync(id);
task2();
task3();
asynctask1.Wait(); // wait for async task to complete
}
如果将async
关键字添加到Load
方法本身,则也可以使用await
关键字。
使Load异步并等待呼叫? 您可以有一个异步void方法,但是如果它是一个异步Task并在调用链中等待它,会更好。
public async void Load(int id)
{
await CallWithAsync(id); // this is async task
task2(); // main thread
task3(); // main thread
}
通过在调用task2()
和task3()
之后等待asynctask1
来使Load
方法async
。 注意, Load
方法现在返回Task
而不是void
public async Task Load(int id)
{
Task asynctask1;
asynctask1 = CallWithAsync(id); // this is async task
task2(); // main thread
task3(); // main thread
var result = await asynctask1;
Console.Writeline(result); //verify returned value of asynctask1 task
}
private async static Task<string> CallWithAsync(int id)
{
string result = "";
try
{
result = await InsertDataAsync(id);
}
catch (Exception ex)
{
//do some error logging
}
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.