【发布时间】:2016-10-14 23:41:32
【问题描述】:
只是希望有人可以在 C# 中使用 async 和 await 时清除返回类型。我了解您有三种返回类型,分别是 Task<T>、Task 和 void。
通过尝试了解这一点,我已阅读您应该只在特殊情况下使用 void(事件处理程序),如果您将同步方法更改为 async 方法,那么您应该将 void 关键字更改为Task.
我的问题是,即使代码完全独立并且结果与继续无关,我是否需要 Task 返回类型?例如,我使用异步方法将一些信息推送到 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()没有使用async/await,它愉快的休眠了4秒,没有锁住UI线程,然后弹出消息框。有什么问题?
【问题讨论】:
-
CallingMethod() 应该使用
async和await。没有这个问题就没有意义了。 -
请注意,“async”与“parellel”不同:“await”行之后的代码在该行等待完成之前不会执行。
-
不需要吗?请检查编辑
-
@Murphybro2:你不应该有一堆“一劳永逸”式的方法;如果这样做,则说明设计有问题。使用同步代码,您只需直接调用
F();对于异步代码,通常的模式是调用await FAsync()。如果您发现自己需要在没有await的情况下做很多FAsync(),这表明您正在尝试做的事情可能有问题。 (而且这个问题没有足够的上下文来诊断这个设计级问题)。 -
嗨@StephenCleary,感谢您的回复。我在写这个问题时有点困惑,并且没有正确复制我的应用程序如何使用 async/await!由于某种原因,我将直接在它们前面的 await 的异步调用误认为是“一劳永逸”!我会为那个举手..
标签: c# .net asynchronous return async-await