gpt4 book ai didi

c# - 阻塞直到事件完成

转载 作者:行者123 更新时间:2023-11-30 14:04:37 25 4
gpt4 key购买 nike

在异步事件完成之前如何阻塞?

这是一种阻塞直到事件被调用的方法,方法是在事件处理程序中设置一个标志并轮询该标志:

private object DoAsynchronousCallSynchronously()
{
int completed = 0;
AsynchronousObject obj = new AsynchronousObject();
obj.OnCompletedCallback += delegate { Interlocked.Increment(ref completed); };
obj.StartWork();

// Busy loop
while (completed == 0)
Thread.Sleep(50);

// StartWork() has completed at this point.
return obj.Result;
}

有没有办法不用轮询来做到这一点?

最佳答案

    private object DoAsynchronousCallSynchronously()
{
AutoResetEvent are = new AutoResetEvent(false);
AsynchronousObject obj = new AsynchronousObject();
obj.OnCompletedCallback += delegate
{
are.Set();
};
obj.StartWork();

are.WaitOne();
// StartWork() has completed at this point.
return obj.Result;
}

关于c# - 阻塞直到事件完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1523148/

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