gpt4 book ai didi

c# - 在 ActionBlock 中等待异步 lambda

转载 作者:太空狗 更新时间:2023-10-29 21:51:01 26 4
gpt4 key购买 nike

我有一个带有 ActionBlock 的 Receiver 类:

public class Receiver<T> : IReceiver<T>
{

private ActionBlock<T> _receiver;

public Task<bool> Send(T item)
{
if(_receiver!=null)
return _receiver.SendAsync(item);

//Do some other stuff her
}

public void Register (Func<T, Task> receiver)
{
_receiver = new ActionBlock<T> (receiver);
}

//...
}

ActionBlock 的 Register-Action 是一个带有 await-Statement 的异步方法:

private static async Task Writer(int num)
{
Console.WriteLine("start " + num);
await Task.Delay(500);
Console.WriteLine("end " + num);
}

现在我想做的是同步等待(如果设置了条件)直到操作方法完成以获得独占行为:

var receiver = new Receiver<int>();
receiver.Register((Func<int, Task) Writer);
receiver.Send(5).Wait(); //does not wait the action-await here!

问题是当“await Task.Delay(500);”语句被执行,“receiver.Post(5).Wait();”不再等待。

我已经尝试了几种变体(TaskCompletionSource、ContinueWith 等),但它不起作用。

有人知道如何解决这个问题吗?

最佳答案

ActionBlock 默认情况下将强制执行独占行为(一次只处理一个项目)。如果您通过“排他性行为”表达其他意思,您可以使用 TaskCompletionSource 在操作完成时通知您的发件人:

... use ActionBlock<Tuple<int, TaskCompletionSource<object>>> and Receiver<Tuple<int, TaskCompletionSource<object>>>
var receiver = new Receiver<Tuple<int, TaskCompletionSource<object>>>();
receiver.Register((Func<Tuple<int, TaskCompletionSource<object>>, Task) Writer);
var tcs = new TaskCompletionSource<object>();
receiver.Send(Tuple.Create(5, tcs));
tcs.Task.Wait(); // if you must

private static async Task Writer(int num, TaskCompletionSource<object> tcs)
{
Console.WriteLine("start " + num);
await Task.Delay(500);
Console.WriteLine("end " + num);
tcs.SetResult(null);
}

或者,您可以使用 AsyncLock ( included in my AsyncEx library ):

private static AsyncLock mutex = new AsyncLock();

private static async Task Writer(int num)
{
using (await mutex.LockAsync())
{
Console.WriteLine("start " + num);
await Task.Delay(500);
Console.WriteLine("end " + num);
}
}

关于c# - 在 ActionBlock 中等待异步 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13704087/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com