2

I have the following code:

Task.Factory.ContinueWhenAll(items.Select(p =>
{
    return CreateItem(p);
}).ToArray(), completedTasks => { Console.WriteLine("completed"); });

Is it possible to convert ContinueWhenAll to a synchronous method? I want to switch back between async and sync.

Edit: I should metnion that each of the "tasks" in the continuewhenall method should be executing synchronously.

4

3 回答 3

1

我想你可以试试这个。

TaskContinuationOptions用于一个简单的场景。

var taskFactory = new TaskFactory(TaskScheduler.Defau

var random = new Random();
var tasks = Enumerable.Range(1, 30).Select(p => {
    return taskFactory.StartNew(() => {
        var timeout = random.Next(5, p * 50);
        Thread.Sleep(timeout / 2);
        Console.WriteLine(@"  1: ID = " + p);
        return p;
    }).ContinueWith(t => {
        Console.WriteLine(@"* 2: ID = " + t.Result);
    }, TaskContinuationOptions.ExecuteSynchronously);
}).ToArray();

Task.WaitAll(tasks);

或将TPL 数据流用于复杂场景。

var step2 = new ActionBlock<int>(i => {
    Thread.Sleep(i);
    Console.WriteLine(@"* 2: ID = " + i);
}, new ExecutionDataflowBlockOptions {
    MaxDegreeOfParallelism = 1,
    //MaxMessagesPerTask = 1
});

var random = new Random();
var tasks = Enumerable.Range(1, 50).Select(p => {
    return Task.Factory.StartNew(() => {
        var timeout = random.Next(5, p * 50);
        Thread.Sleep(timeout / 2);
        Console.WriteLine(@"  1: ID = " + p);
        return p;
    }).ContinueWith(t => {
        Thread.Sleep(t.Result);
        step2.Post(t.Result);
    });
}).ToArray();

await Task.WhenAll(tasks).ContinueWith(t => step2.Complete());
await step2.Completion;
于 2015-01-19T06:51:05.960 回答
1

如果您想保持现有代码完整并具有同步执行的可变选项,您应该进行以下更改:

bool isAsync = false; // some flag to check for async operation

var batch = Task.Factory.ContinueWhenAll(items.Select(p =>
{
    return CreateItem(p);
}).ToArray(), completedTasks => { Console.WriteLine("completed"); });

if (!isAsync)
    batch.Wait();

通过这种方式,您可以以编程方式切换它,而不是通过编辑源代码。并且您可以为这两种方法保持相同的延续代码。

编辑:

这是一个简单的模式,用于将相同的方法表示为同步和异步版本:

public Item CreateItem(string name)
{
    return new Item(name);
}

public Task<Item> CreateItemAsync(string name)
{
    return Task.Factory.StartNew(() => CreateItem(name));
}
于 2013-10-18T19:03:39.187 回答
1

除非我弄错了,这就是你要找的

Task.WaitAll(tasks);
//continuation code here
于 2013-10-18T18:46:37.360 回答