简体   繁体   中英

EventWaitHandle blocking the entire form

I've been looking around for quite some time now, but without any solution..

What I want to achieve, is use an EventWaitHandle class in order to pause one thread.

So, I create two buttons on a form. The first one should send a message, then pause, and the second one should unpause the thread of the first button, which then sends another message. Like that:

using System;
using System.Windows.Forms;
using System.Threading;

namespace Application
{
    public partial class Form1 : Form
    {
        EventWaitHandle wh = new AutoResetEvent(false);

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Thread blocked!");
            wh.WaitOne();
            MessageBox.Show("Thread unblocked!");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            wh.Set();
        }
    }
}

But as soon as the thread gets blocked with the wh.WaitOne() , I can't do anything on the entire form, including pushing the second button or at least closing it..

What did I do wrong? Because I can't seem to find any difference between examples I could find, and my code.

You have only 1 thread. The UI thread. When you block it, you block the entire UI.

You'll have to create a second thread.

Try this:

private void button1_Click(object sender, EventArgs e)
{
    new Thread() {
        void run() {
            MessageBox.Show("Thread blocked!");
            wh.WaitOne();
            MessageBox.Show("Thread unblocked!");
        }
    }.start();
}

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