简体   繁体   中英

C# AutoResetEvent does not reset

I have spent two whole days figuring out why the threading in my WinForms application doesn't work. 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.

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. 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. However the main thread will just stop at autoResetEvent.WaitOne() & remains in waiting state. 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. You should look into other options, such as using async / await .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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