我怎么连锁异步操作,在.NET 4任务并行库? [英] How do I chain Asynchronous Operations with the Task Parallel library in .NET 4?

查看:155
本文介绍了我怎么连锁异步操作,在.NET 4任务并行库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图以编程链的异步操作在C#4,如写入给定的流对象。本来我这个手动,挂钩从一个操作回调到下一个,但我想我会尝试在.NET 4任务并行库,以节省自己的重新发明轮子同时,麻烦

首先,我裹在像这样的任务我异步调用:

 公共静态任务CreateWriteTask(流流,字节[]数据)
{
    返回Task.Factory.FromAsync(stream.BeginWrite,stream.EndWrite,数据,0,data.Length,空);
}
 

延续做出链的同步操作非常简单(如果你能原谅不幸的方法名):

 公共静态任务ChainFlush(流流,任务precedingTask)
{
    返回precedingTask.ContinueWith(X => stream.Flush());
}
 

但没有版本的 Task.ContinueWith 方法接受以同样的方式为 TaskFactory.FromAsync

因此​​,假设我坚持使用第三方物流,我要找的正确实施此方法的:

 公共静态任务ChainWrite(流流,byte []的数据,任务precedingTask)
{
    //?
}
 

解决方案

我的最好的想法至今链创造新的写入任务,然后使用展开扩展方法打开任务<任务&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();
}

这篇关于我怎么连锁异步操作,在.NET 4任务并行库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆