我对我正在使用的ManualResetEvent感到有点困惑,因为它似乎并没有解除阻塞。有人知道为什么会这样吗?
我看到的场景是这样的。实际情况非常复杂,我还没有成功地隔离出一段代码,这些代码可以合理地发布来重现问题。
编辑
我已经更新了下面的代码示例。这是在许多不同的对话框中执行的,我注意到其中一个对话框击中了this.mre.WaitOne();然后我得到了一个“服务器繁忙”对话框,在这个对话框中,我需要按'switch to‘或'retry',这将允许我的代码逐步传递WaitOne()调用,所有这些都会工作。我不知道这有什么关系,但很明显,它有一些重要的意义。
public class A
{
ManualResetEvent mre;
public void Start(ThreadClass tc)
{
this.mre = new ManualResetEvent(false);
tc.Begin();
WebClient wc = new WebClient();
// progress events are pumped to the ThreadClass which then update the Form2.
wc.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(wc_DownloadFileCompleted);
wc.DownloadFileAsync("Src", "Tgt");
this.mre.WaitOne();
}
void void wc_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
try
{
// Do Stuff
}
finally
{
this.mre.Set();
}
}
}
public class ThreadClass
{
Begin()
{
Thread t = new Thread(new ThreadStart(DoWork));
t.Start();
}
private void DoWork()
{
Form f = new Form2();
f.ShowDialog();
// Sits waiting on another ResetEvent to determine when to close the thread.
}
}发布于 2009-07-30 10:20:33
Webclient运行在与调用方相同的线程中,因此线程在WaitOne上被阻塞,它实际上不会为您创建一个新线程。
将代码移动到BackgroundWorker中,或者简单地说,不要阻止而是等待引发DownloadComplete事件。
发布于 2009-07-30 10:35:36
检查您正在设置的MRE实际上与您正在等待的MRE相同。你说这是一个简化的例子--在真正的代码中,你有可能创建两个不同的重置事件吗?这会很明显地破坏事物:)
发布于 2010-06-10 14:41:51
我已经对你的代码做了一点修改,它现在可以正常工作了。问题是,您应该将MRE对象作为DownloadFileAsync方法的用户状态参数传递:
public class A
{
public void Start(ThreadClass tc)
{
ManualResetEvent mre = new ManualResetEvent(false);
WebClient wc = new WebClient();
// progress events are pumped to the ThreadClass which then update the Form2.
wc.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(wc_DownloadFileCompleted);
wc.DownloadFileAsync("Src", "Tgt", mre);
mre.WaitOne();
mre.Close();
}
void void wc_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
try
{
// Do Stuff
}
finally
{
(e.UserState as ManualResetEvent).Set();
}
}
} https://stackoverflow.com/questions/1205674
复制相似问题