且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我怎么连锁异步操作,在.NET 4任务并行库?

更新时间:2023-01-25 15:27:13

我的***的想法至今链创造新的写入任务,然后使用展开扩展方法打开任务<任务&GT ; 工作

 公共静态任务ChainWrite(流流,byte []的数据,任务precedingTask)
{
    返回precedingTask.ContinueWith(X => CreateWriteTask(流,数据))展开()。
}
 

I'm attempting to programmatically chain asynchronous operations in C#4, such as Writes to a given Stream object. I originally did this "manually", hooking callbacks from one operation to the next, but I thought I'd try the .NET 4 Task Parallel Library to save myself the trouble of re-inventing the concurrent wheel.

To start with, I wrap my async calls in Tasks like so:

public static Task CreateWriteTask(Stream stream, byte[] data)
{
    return Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite, data, 0, data.Length, null);
}

Continuations have made chaining synchronous operations very easy (if you'll excuse the unfortunate method name):

public static Task ChainFlush(Stream stream, Task precedingTask)
{
    return precedingTask.ContinueWith(x => stream.Flush());
}

But there is no version of the Task.ContinueWith method that accepts an async operation in the same way as TaskFactory.FromAsync.

So, assuming that I persist with using the TPL, what I'm looking for the correct implementation of this method:

public static Task ChainWrite(Stream stream, byte[] data, Task precedingTask)
{
    //?
}

My best idea so far is to chain the creation of the new write task, then use the Unwrap extension method to turn Task<Task> back into Task:

public static Task ChainWrite(Stream stream, byte[] data, Task precedingTask)
{
    return precedingTask.ContinueWith(x => CreateWriteTask(stream, data)).Unwrap();
}