4

I have created a Windows Service which will interact with a punching machine.The service will connect with the machine and will fetch the data (eg. registered users,attendance logs..etc) from the machine.These methods will work fine.There is an event which will fire when an user punch the machine.So i need to register and create an event an event handler in the service. But in my service it won't fire. I created a sample Windows Form application and write all the same procedure. The event will fire in the form application. My question is

Is there any difference in registering and creating event handler for Windows Service compared to Windows form Application?

Please help me.

 AxLxInterface.SocketInitialize();
 AxLxInterface.WorkIndex = 0;
 AxLxInterface.CardEvent += AxLxInterface_CardEvent;  //event registration(but won't fire
 AxLxInterface.SocketConnect(serverIp, serverPort);  //will connect successfully
 AxLxInterface.DateTimeRead();        //will give the machine date time
 AxLxInterface.PollingStart(000, 000);

Event handler

    public void AxLxInterface_CardEvent(object sender, _DLxInterfaceEvents_CardEventEvent e)
    {
    }
Aneesh
  • 848
  • 1
  • 9
  • 22

2 Answers2

1

I suspect you're interfacing with your device via a legacy helper ActiveX control. Most ActiveX controls are designed to work on an STA thread with functional message loop, and also require thread affinity. This is what your WinForms host app provides.

However, this is not the default execution environment for Windows Service. Thus, you need to create and run an STA thread on your own. This question/answer may further help you:

StaTaskScheduler and STA thread message pumping

Community
  • 1
  • 1
noseratio
  • 59,932
  • 34
  • 208
  • 486
0

Eventing in services is no different; however you need to pay extra attention to any possible exceptions and blocking functions as these can either force your service to stop or prevent it from responding to anything.

One of the ways I found that seems to work well is to have a thread that you start in your OnStart method which waits for Interrupt() or Monitor.Pulse() from your event handler. Then your event handler simply has to gather the required information for executing your tasks and put it in a semaphore.

Forest Kunecke
  • 2,160
  • 15
  • 32