我编写了一个函数,该函数将使用相对较新的异步/等待模式在线程上运行任何函数,并稍后通过可选的回调方法通知调用者。该功能非常简单,如下所示:
private async void DoOperationAsync<T>(Func<T> operation, Action<T> resultAction = null)
{
if (operation == null)
throw new ArgumentNullException("operation");
var result = await Task<T>.Factory.StartNew(operation);
// Notify someone that this finished
if (resultAction != null)
resultAction(result);
}
这对于返回值的函数非常有效。它不适用于返回 void 的函数(或者我不够聪明,无法让它工作)。我可以写一个不假定返回类型的方法的特例。但是,我想知道一些 C# 泛型专家是否可以指出一种在这种情况下处理 void 的方法。有没有不涉及 void 函数的特殊情况的方法?
最佳答案
我有一个 async
/await
intro在我的博客上,您可能会觉得有帮助。
I wrote a function that will, using the relatively new async/await pattern run any function on a thread and notify the caller later via an optional callback method.
这就是 Task.Run
的用途。
I do want that method to run on the calling thread (in my case, it will be the main UI thread of my application in general).
await
已经做到了。
所以,与其编写这样的代码:
DoOperationAsync(() =>
{
// Code that runs on threadpool thread.
return 13;
},
result =>
{
// Code that runs on UI thread.
MessageBox.Show(result.ToString());
});
只需这样做:
var result = await Task.Run(() =>
{
// Code that runs on threadpool thread.
return 13;
});
// Code that runs on UI thread.
MessageBox.Show(result.ToString());
附言Task.Run
已经具有处理有和没有返回值的委托(delegate)所需的所有重载。
关于C# 泛型和 void 的特例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21264712/