0

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.

Aeder
  • 15
  • 5

1 Answers1

1

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();
}
Shloim
  • 5,281
  • 21
  • 36
  • Thanks for a quick answer! But where should I put the Event wait handle class now, in order to only pause the code that executes when the first button is clicked. I tried putting it at different places but with the same result.. – Aeder Nov 22 '15 at 12:19
  • Alright thanks! I didn't knew I could do this as I'm pretty new to multithreading and programming in general. Thanks again, and have a nice day! – Aeder Nov 22 '15 at 13:31