メインスレッドよりも時間がかかる非同期タスクがあります。メインスレッドは非同期タスクの前に終了し、非同期タスクの結果が表示されません。たとえば、非同期タスクが挿入するDBレコードが表示されません。ここでC#で非同期タスクが完了するまでメインスレッドを待機させる方法
が私のコードである
Frameworkの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
}
void
のを返し、注意してください 'asynctask1を待ちますか;'? – zerkms@zerkms 'Load'メソッドは' async'としてマークされていないので、 'await'はこの場合オプションではありません。 –
私は通常、WaitHandleを使用します:https://msdn.microsoft.com/en-us/library/58195swd(v=vs.110).aspx – jdweng