【问题标题】:What is this constructor for: ActionBlock<TInput> Constructor (Func<TInput, Task>)这个构造函数的用途是什么:ActionBlock<TInput> 构造函数 (Func<TInput, Task>)
【发布时间】:2014-01-02 00:48:58
【问题描述】:

我之前通过另一个构造函数使用过 ActionBlock:

ActionBlock&lt;TInput&gt; Constructor (Action&lt;TInput&gt;)

但是对于标题中返回类型为 Task 的那个,我不确定 ActionBlock 对返回的 Task 做了什么。我认为这是为了以某种方式等待提供给构造函数的异步委托?我能拿到吗?

【问题讨论】:

  • 你看过它的文档吗?
  • 是的,它非常稀疏,但我现在找到了答案(现在将回答我自己的问题)。

标签: c# task-parallel-library .net-4.5 tpl-dataflow


【解决方案1】:

好的,我应该猜到它是为了提供异步委托。我一定对它的语法有点陌生。以下是此类代表的一个示例:

var writer = new ActionBlock<string>(async url =>
{
    WebClient wc = new WebClient();
    // using IOCP the thread pool worker thread does return to the pool
    byte[] buffer = await wc.DownloadDataTaskAsync(url);
    string fileName = Path.GetFileName(url);

    string name = @"Images\" + fileName;

    using (Stream srm = File.OpenWrite(name))
    {
        await srm.WriteAsync(buffer, 0, buffer.Length);
    }
});

所以委托 async url => 可以说是有Func&lt;String, Task&gt;的类型。

示例来自:http://blogs.microsoft.co.il/blogs/bnaya/archive/2012/01/28/tpl-dataflow-walkthrough-part-5.aspx

【讨论】:

  • 是的,这可能是最常见的用法。但是任何Task-returning 委托都可以,并且该块将异步等待它完成。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-29
  • 2012-12-28
  • 2011-03-03
  • 2013-04-25
  • 2015-06-05
  • 1970-01-01
  • 2010-11-06
相关资源
最近更新 更多