简体   繁体   中英

How to call a Windows service async from WPF & C#

I have written a Windows service in C#. For testing purposes only, I need to put a temporary WPF front end onto the service. I'm using the ServiceController class from the WPF service to allow the service to be started and stopped, but I need to send data back to the UI during testing for the testers to know when enough data has gone through the service to stop it.

Can use attribute:

[OperationContract (IsOneWay = true)]

Or Async

Add an method inside your service which provides the info you need and then you can choose an event inside your UI to call the method.

Let's say everytime a button is clicked into your UI, you call your service method>

private void Button_Click(object sender, EventArgs e)
{
    yourservice.GetInfo();
}

My suggestion is that you choose the best event that suits your needs, you can even call it in every event that happens inside your UI.

You may create an async method with a while loop inside that keeps checking your service at some given time.

public async Task<int> CheckServiceAsync()
{
   while(condition)
   {
      Thread.Sleep(1000);
      return service.GetInfo();
   }
}

Then in your UI:

TextBox.Text = await CheckServiceAsync();

I think the async way is the best because your UI won't get locked waiting for your service response.

Edit:

You'll need a way to communicate between the 2 applications. I thought you've already had it set up. You'll need a WCF (you can use named pipes) application to communicate between them. Your service and your WPF app are running in different processes. Check this . NetNamedPipeBinding is the fastest for processes on the same machine.

Named pipes (without using WCF) are a bit low level and it can get hard. WCF is easier and you can set up things really fast (once you know what you're doing). Set up your WCF, use the logic I've gave you here in this answer and you'll be good.

Check this WCF tutorial . It has the basics you'll need for your config, but make sure you're using NetNamedPipeBinding as your Binding.

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