C # GlobalResetEvent/WaitHandle,

Source: Internet
Author: User
Tags net thread

C # GlobalResetEvent/WaitHandle,

GlobalResetEvent (Global reset event) is a process similar to the. NET thread.

AutoResetEvent (auto reset event), ManualResetEvent (manual reset event) function set

ARE & MRE is standardized in. NET for thread processing, but at the underlying level it is for System EVENT

The kernel object is a set of function encapsulation, Which is involved by C ++ developers in learning threads,

Fully local to Mutex (Mutex), also known as Mutex lock. It belongs to the same. NET thread processing aspect and lock keyword.

Similar functions,

Due to code specifications, GRE and ARE & MRE depend on abstract WaitHandle

Allows threads to communicate with each other by sending signals. Generally, this mode requires the thread to exclusively access resources.

Call WaitHandle: WaitOne wait signal, internally call WaitForSingleObject

The function waits for the kernel object"

If WaitHandle is not terminated, the thread is blocked and waits for

Thread to send available signals by calling WaitHandle: Set/SetEvent

You can control GRE & ARE & MRE by passing a Boolean value to the constructor.

If the initial status is terminated, the value is true; otherwise, the value is false.

After WaitHandle: Reset/ResetEvent is called, The Termination status is Reset to false,

WaitHandle: Set the termination status after Set to true

The above two figures use GRE to determine whether the process is running or not. If the related words are not checked in the system

MainForm or WebForm. MainForm creates a GRE object after the OnLoad function is triggered.

This is similar to ARE & MRE and is used for thread processing. However, you can understand that the encapsulated code is

ARE method, of course, you can also change to MRE method,

The second parameter bManualReset of CreateEvent is a Boolean value. If it is true, MRE is used.

False: Use the ARE method.

Sample Code:

    public static class Program    {        private static GlobalResetEvent greUnk = new GlobalResetEvent("gre_unk", false);        [STAThread]        public static void Main()        {            ThreadPool.QueueUserWorkItem(delegate            {                Thread.Sleep(1200);                Console.WriteLine("test.");                greUnk.Set();            });            greUnk.WaitOne();            Console.WriteLine("ok.");            Console.ReadKey(false);        }    }

GRE code:

#pragma warning disable 0618namespace Themyth_Chrome.Thread{    using Microsoft.Win32.SafeHandles;    using System;    using System.Runtime.InteropServices;    using System.Threading;    public partial class GlobalResetEvent : WaitHandle, IDisposable    {        private abstract partial class NativeMethod        {            [DllImport("kernel32.dll", SetLastError = true)]            [return: MarshalAs(UnmanagedType.Bool)]            public static extern bool CloseHandle(IntPtr hObject);            [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]            public static extern IntPtr OpenEvent(uint dwDesiredAccess, bool bInheritHandle, string lpName);            [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]            public static extern IntPtr CreateEvent(int lpEventAttributes, bool bManualReset, bool bInitialState, string lpName);            [DllImport("kernel32.dll", SetLastError = true)]            [return: MarshalAs(UnmanagedType.Bool)]            public static extern bool SetEvent(IntPtr hEvent);            [DllImport("kernel32.dll", SetLastError = true)]            [return: MarshalAs(UnmanagedType.Bool)]            public static extern bool ResetEvent(IntPtr hEvent);            [DllImport("kernel32.dll", SetLastError = true)]            public static extern int WaitForSingleObject(IntPtr hHandle, int dwMilliseconds);            public const int WAIT_OBJECT_0 = 0;            public const int NULL = 0;            public const int INFINITE = -1;            public const int EVENT_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | (SYNCHRONIZE | 3));            public const int STANDARD_RIGHTS_REQUIRED = 983040;            public const int SYNCHRONIZE = 1048576;        }    }    public partial class GlobalResetEvent    {        public override void Close()        {            this.SafeWaitHandle.Dispose();            NativeMethod.CloseHandle(Handle);        }        public bool Set()        {                       return NativeMethod.SetEvent(Handle);        }        public bool Reset()        {            return NativeMethod.ResetEvent(Handle);        }        public override bool WaitOne()        {            return this.WaitOne(NativeMethod.INFINITE);        }        public override bool WaitOne(int millisecondsTimeout)        {            return NativeMethod.WaitForSingleObject(Handle, millisecondsTimeout) == NativeMethod.WAIT_OBJECT_0;        }    }    public partial class GlobalResetEvent    {        public GlobalResetEvent(IntPtr eventHandle)        {            if (eventHandle == IntPtr.Zero)                throw new Exception("event handle is invalid.");            this.Handle = eventHandle;            this.SafeWaitHandle = new SafeWaitHandle(eventHandle, true);        }        public GlobalResetEvent(string name, bool initialState)        {            if ((this.Handle = NativeMethod.CreateEvent(NativeMethod.NULL, false, initialState, name)) == IntPtr.Zero)                throw new Exception("create event failed.");            this.SafeWaitHandle = new SafeWaitHandle(Handle, true);        }        public static GlobalResetEvent Open(string name)        {            IntPtr hUnkEvent = NativeMethod.OpenEvent(NativeMethod.EVENT_ALL_ACCESS, false, name);            if (hUnkEvent == IntPtr.Zero)                throw new Exception("open event failed.");            return new GlobalResetEvent(hUnkEvent);        }        public static bool OpenExisting(string name)        {            IntPtr hUnkEvent = NativeMethod.OpenEvent(NativeMethod.EVENT_ALL_ACCESS, false, name);            return hUnkEvent != IntPtr.Zero;        }        public static GlobalResetEvent Create(IntPtr eventHandle)        {            return new GlobalResetEvent(eventHandle);        }        public static GlobalResetEvent Create(string name, bool initialState)        {            return new GlobalResetEvent(name, initialState);        }    }}



 

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.