简体   繁体   English

C# AutoResetEvent 不重置

[英]C# AutoResetEvent does not reset

I have spent two whole days figuring out why the threading in my WinForms application doesn't work.我花了整整两天的时间弄清楚为什么我的 WinForms 应用程序中的线程不起作用。 I really need some help here.我真的需要一些帮助。

In my application, button1_Click event will call a method but if the method runs for too long, I want to abort it.在我的应用程序中,button1_Click 事件将调用一个方法,但如果该方法运行时间过长,我想中止它。

private void button1_Click(object sender, EventArgs e)
{
    button1.Enabled = false; 
    Thread t1 = new Thread(new ThreadStart(ExtractData));
    t1.Start();

    //Wait for 5 seconds, if t1 is not finished executing, abort the thread
    autoResetEvent.WaitOne(5000);
    if (autoResetEvent.WaitOne()== false)
    {
        t1.Abort();
    }
    button1.Enabled = true; 
}

private void ExtractData()
{
    //Get data from web service..

    autoResetEvent.Set();
}

I consider button1_Click event as my main thread and ExtractData() will be in thread t1.我认为 button1_Click 事件是我的主线程,而 ExtractData() 将在线程 t1 中。 After ExtractData() is finished doing it's work, I want autoResetEvent.Set() to wake up autoResetEvent.WaitOne() in the main thread & therefore the main thread execution can be finished. ExtractData() 完成它的工作后,我希望 autoResetEvent.Set() 唤醒主线程中的 autoResetEvent.WaitOne() & 因此主线程执行可以完成。 However the main thread will just stop at autoResetEvent.WaitOne() & remains in waiting state.然而,主线程将在 autoResetEvent.WaitOne() 处停止并保持等待状态。 Did I do anything wrong?我做错了什么吗?

You're waiting on the event twice, and after the first time the event has been reset, as it is an auto reset event.您正在等待该事件两次,并且在第一次事件被重置之后,因为它是一个自动重置事件。 Change this:改变这个:

autoResetEvent.WaitOne(5000);
if (autoResetEvent.WaitOne()== false)
{
    t1.Abort();
}

to

if (autoResetEvent.WaitOne(5000)== false)
{
    t1.Abort();
}

So that you only wait on it once.这样你就只等一次。

Also, as others have mentioned, your code is blocking the gui thread for the entire 5 seconds that you wait, meaning your applcation will become unresponsive.此外,正如其他人所提到的,您的代码在您等待的整个 5 秒内都在阻塞 gui 线程,这意味着您的应用程序将变得无响应。 You should look into other options, such as using async / await .您应该查看其他选项,例如使用async / await

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM