简体   繁体   中英

Closing WPF Application Via WCF Takes Too Long

I have a WPF application which hosts a WCF service. Part of this service is the ability to close the application from another client (running on the same machine). I use the following code to close it in the WCF service:

MainWindow form = MainWindow.CurrentInstance;
form.MySynchronizationContext.Send(_ => form.CloseWindow(), null);

My MainWindow is setup with a static CurrentInstance variable so I can get the current window and then I call a method I added called CloseWindow via a SynchronizationContext. This all works fine except it takes a long time to close (about 10 seconds) which is a lot longer than if you close the app manually.

Is there a better way of doing this which is more responsive?

Update - At the moment the CloseWindow function just calls Close() but it may do a few other bits eventually.

I have found the solution to this problem but I don't fully understand why this was a problem in the first place as it should of already been the case.

The service was declared with the following

[ServiceBehavior(UseSynchronizationContext = false)]

It is my understanding that with this statement, even if the service was created within the MainWindow class, it would still be forced to create it's own thread rather than being run on the UI thread. It turns out this doesn't seem to be the case. I have since moved the host creation outside the MainWindow class before its creation and now the Close happens almost immediately. I can only assume (without digging deeper) that the UseSynchronizationContext = false isn't forcing the service host to not be created on the UI thread.

Although this solves the problem, I would love to know why setting the service behaviour is making no difference.

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