Har*_*rry 4 .net c# events controls multithreading
我有自定义浏览器类,它能够根据浏览的页面状态触发大量事件.现在我需要使用我的浏览器在这个网页上执行一些操作,但是它们必须按顺序运行,每个操作都需要前一个操作的数据.实现这一目标的最简单方法是使同步方法等待浏览器完成其工作.我这样做了:
public incomplete class MyClass {
// (...) lots of stuff comes here, it's a web browser :)
public bool MySyncMethod(object data) {
bool success = false;
bool wait = true;
MyEventHandler = new EventHandler((o, e) => {
data = MyEventProvidedData; // belive me, it's threre when it fired
success = true; // let's assume it always succeed
wait = false; // now we can move on to the rest of our long chain
});
// (...) here I have some more event handlers which can end my method...
MyAsyncMethod(data); // so it started and will fire MyEventHandler soon
while (wait) System.Threading.Thread.Sleep(100);
return success;
}
}
Run Code Online (Sandbox Code Playgroud)
但这里似乎有些不对劲.如果我使用线程,我只是放置myThread.Join()而不是我的while循环,它会等待我的线程完成.它是否与Thread.Join()类似,可以与控件触发的事件一起使用?有什么东西可以用而不是while循环吗?这是实现我的目标更清洁的方式吗?上面的代码适用于真正的应用程序,但我认为它不是最佳的.
并且有一个很好的理由我不在这里使用线程 - 线程和ActiveX控件之间的所有通信必须是线程安全的,这并非易事.是的,我试过:)这段代码是调试的地狱,所以我决定重写它.
尝试使用ManualResetEvent:
var wait = new ManualResetEvent(false);
var handler = new EventHandler((o, e) => wait.Set());
MyAsyncMethod(data, handler); // so it started and will fire handler soon
wait.WaitOne();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9578 次 |
最近记录: |