Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call method from running windows service

I have created and started windows service Service1 (with exe as MyService.exe) using c# 2005. . I have included a method GetMyRandomNumber() that returns a random double value.

The problem here is how could use this running service and how could i call the method.

I have tried adding reference of MyService.exe and access the method as -

Service1 s = new Service1();
MessageBox.Show(s.GetMyRandomNumber().ToString());

But found that the method is not called from the running instance of the service i.e. even though i stop the service the statements are executed.

Could someone explain me how can I call the method from running instance of the service.

Thanks for sharing your valuable time.

like image 303
IrfanRaza Avatar asked Dec 30 '09 08:12

IrfanRaza


People also ask

How do you call a Windows service method in C#?

Choose "Visual C#" >> "Windows" project type and select "Windows Service" from the right hand side and name the project "TestWindowsService" as shown in the following screenshot. After you click "OK", the project will be created and you will see the design view of the service as shown in the following screen.


4 Answers

In your code, you aren't actually calling the service, instead you are referencing the executable and invoking a method from that assembly (at run time the .NET Framework will use a local assembly to execute the code, not your running service).

To do what you want, you have a number of options.

In .NET 2.0, you would make use of .NET Remoting. You create a remoting interface, which other assemblies can use to invoke methods across executables.

In .NET 3.0, remoting was replaced by WCF. Your service would become a WCF service, which would expose the GetRandomNumber() as part of its data contract. Applications can consume the contract and connect to your service to call the method.

There are a number of good tutorials on the web for both .NET Remoting or its replacement, Windows Communication Foundation.

like image 127
Alan Avatar answered Sep 30 '22 09:09

Alan


You should have a look at Remoting

like image 29
Adriaan Stander Avatar answered Sep 30 '22 09:09

Adriaan Stander


WCF will be an overkill for communication on the same computer. Pipes is a simpler and more effective solution.

like image 40
Giorgi Avatar answered Sep 30 '22 11:09

Giorgi


Communicating with a running service is no different from invoking methods on any other running process. That means that you will need to dig out your standard tools for process-to-process communication.

Windows Communication Foundation (WCF) would be my default choice. You can host a WCF service in your Windows Service and expose it through a Named Pipe endpoint for efficient communication.

like image 24
Mark Seemann Avatar answered Sep 30 '22 10:09

Mark Seemann