samedi 11 avril 2015

Using EventWaitHanldes between Windows Service and Windows Application

I have a requirement to send signal from a Windows Service to a Windows console/Forms application using Named Events. I created a common NamedEvents class library which has the implementation to create events. The issue is that my windows service is not creating event. If I create another Windows Forms application(in place of windows service) to create a event then it works fine. But with Windows Service it doesn't seem to work, Can please someone advice me if I am missing something in my code



public static class NamedEvents
{
public static EventWaitHandle OpenOrCreate(string name, bool initialState, EventResetMode mode)
{
EventWaitHandle ewh = null;
try
{
ewh = EventWaitHandle.OpenExisting(name);
}
catch (WaitHandleCannotBeOpenedException)
{
ewh = new EventWaitHandle(initialState, mode, name);
}

return ewh;
}

public static EventWaitHandle OpenOrWait(string name)
{
EventWaitHandle ewh = null;

while (null == ewh)
{
try
{
ewh = EventWaitHandle.OpenExisting(name);
}
catch (WaitHandleCannotBeOpenedException)
{
Thread.Sleep(50);
}
}

return ewh;
}
}


Windows Service Code:



public void SetSignalToClient()
{
EventWaitHandle completedA = NamedEvents.OpenOrCreate("CompletedA", false, EventResetMode.ManualReset);
completedA.Set();
completedA.Close();

}


Windows Forms Application:



public Form1()
{
InitializeComponent();
new Task((o) => SubscribeToAsyncEvents(),
new System.Threading.CancellationToken()).Start();
}



private void SubscribeToAsyncEvents()
{
while (true)
{
EventWaitHandle completedA = NamedEvents.OpenOrWait("CompletedA");
completedA.WaitOne();
if (textBox1.InvokeRequired)

{

textBox1.Invoke((MethodInvoker)delegate { textBox1.Text = "received"; });

}
completedA.Close();
}
}

Aucun commentaire:

Enregistrer un commentaire