C# 泛型和 void 的特例

标签 c# generics 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);
}

这对于返回值的函数非常有效。它不适用于返回 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/

相关文章:

javascript - 获取在 Promise.race 中完成了哪个 promise

c# - HtmlAgilityPack 给出格式错误的 html 问题

c# - "where NOT derived from"是否有通用类型约束?

c# - 使图像路径唯一

java - 什么是原始类型,为什么我们不应该使用它呢?

c# - List<T> 其中 T 是自定义对象。按属性删除重复项

c# - 当某些任务可以为空时如何WhenAll?

javascript - 当我的异步函数前面没有 await 时,try catch block 会捕获错误吗?

c# - 'GraphicsPath.AddString' 中的字体比通常的字体小

c# - 无法使用 asp.net 中的 twilio 短信服务发送回复短信