C # Reader thread (synchronized with AutoResetEvent) (reproduced)

Source: Internet
Author: User
Tags compact

C # Reader thread (synchronization with AutoResetEvent implementation)

1. AutoResetEvent Introduction

Notifies the waiting thread that an event has occurred. This class cannot be inherited.

Introduction to Common methods:

AutoResetEvent (bool initialstate): A constructor that initializes a new instance of the class with a Boolean value that indicates whether the initial state is set to signaled.
False: No signal, the WaitOne method of the child thread is not automatically called
True: There is a signal that the WaitOne method of the child thread is automatically called

public bool Reset (): Sets the event state to a non-terminating state, causes the thread to block, or returns true if the operation succeeds;
public bool Set (): Sets the event state to the signaled state, allows one or more waiting threads to continue, or returns true if the operation succeeds; otherwise, returns false.
A single thread is freed for eventwaithandle,set methods that have Eventresetmode.autoreset (including AutoResetEvent). If there is no waiting thread, the wait handle remains signaled until a thread tries to wait for it, or until its Reset method is called.


For EventWaitHandle with Eventresetmode.manualreset (including ManualResetEvent), calling the set method causes the wait handle to remain signaled until its Reset method is called.

WaitOne method
When overridden in a derived class, blocks the current thread until the current WaitHandle receives a signal.

WaitHandle.WaitOne () When overridden in a derived class, blocks the current thread until the current WaitHandle receives a signal. Supported by the. NET Compact Framework.
When WaitHandle.WaitOne (Int32, Boolean) is overridden in a derived class, blocks the current thread until the current WaitHandle receives a signal, uses a 32-bit signed integer to measure the time interval, and specifies whether to exit the synchronization domain before waiting. Supported by the. NET Compact Framework.
When WaitHandle.WaitOne (TimeSpan, Boolean) is overridden in a derived class, blocks the current thread until the current instance receives a signal, uses a TimeSpan to measure the interval, and specifies whether to exit the synchronization domain before waiting.
2. Reader-Writer Threading Example

In this example, the main thread is a write thread that assigns a value (that is, a variable in this case) to a data (that is, a write action), while the read thread waits for the write thread to send a notification each time the data is written, and when the thread is notified, the data is read out and displayed.


Using System;
Using System.Collections.Generic;
Using System.Text;

Using System.Threading;

Namespace Testautoresetevent
{
///
Reader thread
The main thread writes, the child threads read, and the read thread can read the data only after it has been written
///
Class Program
{
Write thread writes data to MyData
static int myData = 100;

Read and write times
const int readwritecount = 10;

False: No signal at initial time
static AutoResetEvent AutoResetEvent = new AutoResetEvent (false);

static void Main (string[] args)
{
Open a read thread (child thread)
Thread readerthread = new Thread (new ThreadStart (Readthreadproc));
Readerthread.name = "Readerthread";
Readerthread.start ();

for (int i = 1; I <= readwritecount; i++)
{
Console.WriteLine ("Mainthread writing: {0}", i);

The primary (write) thread writes data to
MyData = i;

Main (write) line Cheng signal, indicating that the value has been written
That is, notifies the waiting line that the threads event occurred
AutoResetEvent.Set ();

Thread.Sleep (0);
}

           //terminating Threads
             Readerthread.abort ();
       }

static void Readthreadproc ()
{
while (true)
{
The read thread waits before the data is written (actually waits for the write thread to send out a signal that the data is written)
Autoresetevent.waitone ();
Console.WriteLine ("{0} reading: {1}", Thread.CurrentThread.Name, MyData);
}
}
}
The results of the operation are as follows:

It can be seen from the running result that the data written by the write thread is lost, mainly because the write thread does not leave enough time for the read thread to read.

3. Modify the 1


Change the main thread sleep time to a value other than 0 to observe the running result.

Using System;
Using System.Collections.Generic;
Using System.Text;

Using System.Threading;

Namespace Testautoresetevent
{
///
Reader thread
The main thread writes, the child threads read, and the read thread can read the data only after it has been written
///
Class Program
{
Write thread writes data to MyData
static int myData = 100;

Read and write times
const int readwritecount = 10;

False: No signal at initial time
static AutoResetEvent AutoResetEvent = new AutoResetEvent (false);

static void Main (string[] args)
{
Open a read thread (child thread)
Thread readerthread = new Thread (new ThreadStart (Readthreadproc));
Readerthread.name = "Readerthread";
Readerthread.start ();

for (int i = 1; I <= readwritecount; i++)
{
Console.WriteLine ("Mainthread writing: {0}", i);

The primary (write) thread writes data to
MyData = i;

Main (write) line Cheng signal, indicating that the value has been written
That is, notifies the waiting line that the threads event occurred
AutoResetEvent.Set ();

Thread.Sleep (1);
}

Terminating a thread
Readerthread.abort ();
}

static void Readthreadproc ()
{
while (true)
{
The read thread waits before the data is written (actually waits for the write thread to send out a signal that the data is written)
Autoresetevent.waitone ();
Console.WriteLine ("{0} reading: {1}", Thread.CurrentThread.Name, MyData);
}
}
}
The results of the operation are as follows:

As a result, when the main thread sleeps longer than 0, the read thread has enough time to read the data written by the write thread. The length of the sleep time can be set according to the actual application of the neutron thread calculation amount.

4. Modify the 1 again


Does the main thread not sleep at all after it has finished writing the data? What's going to happen at this time?

Using System;
Using System.Collections.Generic;
Using System.Text;

Using System.Threading;

Namespace Testautoresetevent
{
///
Reader thread
The main thread writes, the child threads read, and the read thread can read the data only after it has been written
///
Class Program
{
Write thread writes data to MyData
static int myData = 100;

Read and write times
const int readwritecount = 10;

False: No signal at initial time
static AutoResetEvent AutoResetEvent = new AutoResetEvent (false);

static void Main (string[] args)
{
Open a read thread (child thread)
Thread readerthread = new Thread (new ThreadStart (Readthreadproc));
Readerthread.name = "Readerthread";
Readerthread.start ();

for (int i = 1; I <= readwritecount; i++)
{
Console.WriteLine ("Mainthread writing: {0}", i);

The primary (write) thread writes data to
MyData = i;

Main (write) line Cheng signal, indicating that the value has been written
That is, notifies the waiting line that the threads event occurred
AutoResetEvent.Set ();

Thread.Sleep (1);
}

Terminating a thread
Readerthread.abort ();
}

static void Readthreadproc ()
{
while (true)
{
The read thread waits before the data is written (actually waits for the write thread to send out a signal that the data is written)
Autoresetevent.waitone ();
Console.WriteLine ("{0} reading: {1}", Thread.CurrentThread.Name, MyData);
}
}
}
}

The results of the operation are as follows:

As a result, sleep deprivation and sleep time are 0 (ie, thread.sleep (0);) The results are not much, just not sleep lost more data.

5. Re-Modify the 1


Set the parameter of the constructor passed to AutoResetEvent to true to observe the result of the run.

Using System;
Using System.Collections.Generic;
Using System.Text;

Using System.Threading;

Namespace Testautoresetevent
{
///
Reader thread
The main thread writes, the child threads read, and the read thread can read the data only after it has been written
///
Class Program
{
Write thread writes data to MyData
static int myData = 100;

Read and write times
const int readwritecount = 10;

False: No signal at initial time
static AutoResetEvent AutoResetEvent = new AutoResetEvent (true);

static void Main (string[] args)
{
Open a read thread (child thread)
Thread readerthread = new Thread (new ThreadStart (Readthreadproc));
Readerthread.name = "Readerthread";
Readerthread.start ();

for (int i = 1; I <= readwritecount; i++)
{
Console.WriteLine ("Mainthread writing: {0}", i);

The primary (write) thread writes data to
MyData = i;

Main (write) line Cheng signal, indicating that the value has been written
That is, notifies the waiting line that the threads event occurred
AutoResetEvent.Set ();

Thread.Sleep (0);
}

Terminating a thread
Readerthread.abort ();
}

static void Readthreadproc ()
{
while (true)
{
The read thread waits before the data is written (actually waits for the write thread to send out a signal that the data is written)
Autoresetevent.waitone ();
Console.WriteLine ("{0} reading: {1}", Thread.CurrentThread.Name, MyData);
}
}
}
}

The results of the operation are as follows:

If the main thread's sleep time is changed to any non-0 value, the result of the operation is shown.

6. Other modifications

The main thread calls the set method of the AutoResetEvent object to delete, respectively, the parameters of the AutoResetEvent constructor are false and true to observe the running result.

To false, the result of the run is as shown.

To true, the result of the run is as shown.

At this point, I think we should understand the meaning of the parameters of the AutoResetEvent constructor.
False: No signal, the WaitOne method of the child thread is not automatically called;
True: There is a signal that the WaitOne method of the child thread will be called automatically.

This article from Csdn Blog, reproduced please indicate the source: http://blog.csdn.net/livelylittlefish/archive/2008/07/30/2735440.aspx

C # Reader thread (synchronized with AutoResetEvent) (reproduced)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.