等待回调

时间:2019-12-17 13:27:15

标签: c# wait

我有一个服务,可以接收请求并逐步处理它们(使用ActionBlock)。

有时,我需要等到处理完毕。我可以选择输入回调。有没有一种方法可以暂停运行,直到调用回调?

类似的东西,但是更好:

    bool complete = true;
    service.AddRequest(new ServiceRequest()
    {
        OnComplete = (req) =>
        {
            complete = true;
        }
    });
    while (!complete) Thread.Sleep(100);

上下文的较长代码:

public class Service
{
    protected ActionBlock<ServiceRequest> Requests;
    public Service()
    {
        Requests = new ActionBlock<ServiceRequest>(req => {
            // do noting
            Thread.Sleep(1000);
            req.OnComplete?.Invoke(req);
        });
    }

    public void AddRequest(ServiceRequest serviceRequest) => Requests.Post(serviceRequest);
}

public class ServiceRequest
{
    public Action<ServiceRequest> OnComplete;
    string Foo;
}

public class App
{
    public static void Start()
    {
        var service = new Service();
        service.AddRequest(new ServiceRequest());
        // I need to wait for processing

        // smelly code!!
        bool complete = true;
        service.AddRequest(new ServiceRequest()
        {
            OnComplete = (req) =>
            {
                complete = true;
            }
        });
        while (!complete) Thread.Sleep(100);
        // smelly code!! end
    }
}

1 个答案:

答案 0 :(得分:2)

您的代码有误,complete的初始值应为false;)

bool complete = false; // initial value
service.AddRequest(new ServiceRequest()
{
    OnComplete = (req) =>
    {
        complete = true;
    }
});
while (!complete) Thread.Sleep(100);

要防止主动等待循环,您可以使用AutoResetEvent

AutoResetEvent completedEv = new AutoResetEvent();
service.AddRequest(new ServiceRequest()
{
    OnComplete = (req) =>
    {
        completedEv.Set();
    }
});

completedEv.WaitOne();

注意:AutoResetEvent实现了IDisposable接口,因此必须确保即使在错误情况下也可以将其丢弃。