简体   繁体   中英

Named Events to notify Windows Application

I have a requirement to send signal from Windows Service to a Windows console/Forms application using Named Events like Auto Reset Events and Manual reset events. I understand AutoResetEvents and ManualResetEvents are mainly used for thread synchronization, but now I have a requirement to use named events to signal a Windows Forms application. I EventWaitHandler and wrote code which can do this, by my windows service is crashing at the SetSignalToClient method call

In Event Viewer I found the exception as: Exception Info: System.Threading.WaitHandleCannotBeOpenedException

Windows Service Code:

public void SetSignalToClient()
{

 System.Threading.EventWaitHandle wh =  EventWaitHandle.OpenExisting("MyEventName", EventWaitHandleRights.Modify);

wh.Set();
}

Windows Forms Application:

public void ReceiveSignalFromClient()
{
  textBox1.Text = "Successful";
  while (true)
   {
    EventWaitHandle wh = new EventWaitHandle(false,  EventResetMode.AutoReset, "MyEventName");
    wh.WaitOne(); 
    textBox1.Text = "Failed"; 
   }

}

Thanks in advance...

This question is possibly too broad, depending on what level of detail you were actually hoping to obtain in an answer. Here is a not broad answer… :)

As you probably know, the Windows "event" object is simply a waitable object. Signaling it allows a thread to proceed past a wait call; this can be used for synchronization of algorithms or for one process or thread to control the execution state (paused or running) of a cooperating thread.

One would use a named event between processes exactly as one would use them within the same process. The only difference is that being named, two different processes can access the same event object, and of course Windows (and the .NET wrapper) provides a mechanism to attempt to create the event, retrieving an already-created one should it already exist.

The only "notification" that can be obtained through the use of an event object is for a thread in the process to wait on the object, and then for that wait to be completed with either a timeout or some other thread (possibly in another process, for a named event) to signal the event object. This notification works identically whether the signaling thread is in the same process or a different one.

If you need more specific advice than that, you will need to provide a more specific question than you have so far.

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