简体   繁体   English

通过WCF关闭WPF应用程序花费的时间太长

[英]Closing WPF Application Via WCF Takes Too Long

I have a WPF application which hosts a WCF service. 我有一个托管WCF服务的WPF应用程序。 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: 我使用以下代码在WCF服务中将其关闭:

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. 我的MainWindow是使用静态CurrentInstance变量设置的,因此我可以获取当前窗口,然后通过SynchronizationContext调用添加的方法CloseWindow。 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. 所有这些都可以正常工作,只是关闭它需要很长时间(大约10秒),这比手动关闭应用程序要长得多。

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. 更新-目前,CloseWindow函数仅调用Close(),但最终可能还会执行其他一些操作。

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. 我的理解是,即使使用MainWindow类创建了该语句,该服务仍将被迫创建自己的线程,而不是在UI线程上运行。 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. 从那以后,我在创建主机之前将主机创建移到了MainWindow类之外,现在关闭几乎立即发生。 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. 我只能假定(无需更深入地研究)UseSynchronizationContext = false不会强制在UI线程上不创建服务主机。

Although this solves the problem, I would love to know why setting the service behaviour is making no difference. 尽管这可以解决问题,但我很想知道为什么设置服务行为没有任何区别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM