只希望在C#中使用异步等待时有人可以清除返回类型。我明白你有三种返回类型:任务< T>,任务和无效。从试图了解这一点我已经读过你应该只在特殊情况下使用void(事件处理程序),如果你正在改变同步方法为异步方法,那么你应该将一个void关键字更改为任务。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;
}
如果它是不明确的,通过各种手段只是说和我我会尽量整理一下。多谢你们。
编辑:
private void CallingMethod()
{
AsyncMethod();
}
private async void AsyncMethod()
{
await LongRunningMethod();
}
private async Task LongRunningMethod()
{
await Task.Run(() =>
{
Thread.Sleep(4000);
});
MessageBox.Show("Done!");
}
在响应于第一评论,上述CallingMethod不使用等待/异步和它高兴地睡4秒钟,而不锁定了GUI线程,然后弹出的消息框。有什么问题?
CallingMethod()应该使用'async'和'await'。没有这个问题就没有什么意义。 –
请注意,“异步”与“parellel”不同:“await”行之后的代码在该行完成等待之前不会执行。 –
它不必?请检查编辑 – Murphybro2