C#泛型和void的特殊情况

Lou*_*uis 1 c# generics async-await

我编写了一个函数,它将使用相对较新的async/await模式在线程上运行任何函数,并稍后通过可选的回调方法通知调用者.该功能非常简单,如下所示:

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);
}
Run Code Online (Sandbox Code Playgroud)

这对于返回值的函数非常有效.它不适用于返回void的函数(或者我可能不够聪明,无法使其工作).我可以编写一个不承担返回类型的特殊情况.但是,我想知道一些C#泛型专家是否可以在这种情况下指出一种处理void的方法.是否有工作方式不涉及无效功能的特殊情况?

Ste*_*ary 5

我在我的博客上有一个async/ await介绍,你可能会觉得有帮助.

我编写了一个函数,它将使用相对较新的async/await模式在线程上运行任何函数,并稍后通过可选的回调方法通知调用者.

Task.Run是为了什么.

我确实希望该方法在调用线程上运行(在我的情况下,它通常是我的应用程序的主UI线程).

并且await已经这样做了.

所以,而不是像这样编写代码:

DoOperationAsync(() =>
{
  // Code that runs on threadpool thread.
  return 13;
},
result =>
{
  // Code that runs on UI thread.
  MessageBox.Show(result.ToString());
});
Run Code Online (Sandbox Code Playgroud)

这样做:

var result = await Task.Run(() =>
{
  // Code that runs on threadpool thread.
  return 13;
});
// Code that runs on UI thread.
MessageBox.Show(result.ToString());
Run Code Online (Sandbox Code Playgroud)

PS Task.Run已经具有处理具有和不具有返回值的委托的所有必要重载.