C#で非同期待機を使用する場合、誰かが戻り値の型を整理できることを期待しています。タスク< T>、タスクと無効の3つの戻り値の型があることを理解しています。これについて学ぶことから、特殊な状況(イベントハンドラ)でのみvoidを使用し、同期メソッドを非同期メソッドに変更する場合はvoidキーワードをTaskに変更する必要があります。C#.NET非同期返される型を返します
私の質問は、コードが完全に独立しており、結果が継続のために重要ではないのに、タスクの戻り値の型が必要ですか?たとえば、非同期メソッドを使用していくつかの情報をWebサービスにプッシュするとします。
私が説明するために、小さな例を作成しました:
private void CallingMethod()
{
AsyncMethod();
AsyncTaskMethod(); // any difference between doing these? (not exc handling)
var task = AsyncTaskMethod(); // should I do anything with this task
// before I continue? Or is it simply
// just to show the user that it's async??
// continue with unrelated code that doesnt require task or any code from above
}
private async void AsyncMethod() // is void okay?
{
await LongRunningMethod();
// do other stuff
}
private async Task AsyncTaskMethod() // or should it be Task?
{
await LongRunningMethod();
// do other stuff
}
private async Task LongRunningMethod()
{
// do long running code
}
私のアプリケーションは、そのようなメソッドをたくさん持っている:
private void BigMethod()
{
DoStuff();
DoMoreStuff();
AsyncMethod(); // is this right? Or should I have the task declaration too?
UnrelatedStuff();
}
private async Task AsyncMethod() // should this return task?
{
var result = await GetUserId();
if (result == null)
return;
MyUserId = result;
}
private async Task<int> GetUserId()
{
// do long running code
return 1;
}
それはすべての手段によって、はっきりしていない場合は、単に言うと、Iそれをちょっと整理しよう。みんなありがとう。
EDIT:CallingMethod上記使用していない最初のコメントに応答して
private void CallingMethod()
{
AsyncMethod();
}
private async void AsyncMethod()
{
await LongRunningMethod();
}
private async Task LongRunningMethod()
{
await Task.Run(() =>
{
Thread.Sleep(4000);
});
MessageBox.Show("Done!");
}
は/非同期待って、それは喜んで、メッセージボックスをポップアップ、GUIスレッドをロックせずに4秒間スリープ。どうしたの?
CallingMethod()は 'async'と' await'を使うべきです。それがなければ質問はほとんど意味がない。 –
"async"は "parellel"と同じではないことに注意してください。 "await"行の後のコードは、その行が待たれるまで実行されません。 –
これは必要ありませんか?編集を確認してください – Murphybro2