Tuesday, January 21, 2014

Thread Synchronization with AutoResetEvent

If one has multiple threads running in a program often a synchronization is needed, meaining: A thread is supposed to only continue if a specific event or similiar has occured.
To do this, one could either write an infinite loop by hand and in this way wait for the event.
But an easier and also more efficient possibility provides the class AutoResetEvent. This realizes exactly this, it provides functions with which a thread can wait for an event. When waiting the thread is blocked and eventually woken up again when the event occurs.
An instance of the class AutoResetEvent saves the current state of the event internally, in the constructor this can be initialized (false = waiting, true = event occured).
Via the function WaitOne() the current thread waits until the event occurs. This can be signaled via Set(). Reset() deletes the event then again.
In the following example the main program starts a new thread. This waits in a loop for the occurence of Event1, which is fired by a click on the button. Then a message is displayed:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;

namespace ThreadSynchronization
    public partial class Form1 : Form
        public Form1()

        private AutoResetEvent Event1 = new AutoResetEvent(false);

        private void Form1_Load(object sender, EventArgs e)
            Thread Thread1 = new Thread(Looper);

        private void Looper()
            while (true)

        private void button1_Click(object sender, EventArgs e)

No comments:

Post a Comment