我有一个服务,可以接收请求并逐步处理它们(使用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
}
}
答案 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
接口,因此必须确保即使在错误情况下也可以将其丢弃。