Windows 关闭时调用 WCF 方法有时会失败
我有一个 WPF 应用程序,它在 Windows 关闭(System.Windows.Application.Current.SessionEnding 事件)时异步调用 WCF 方法,然后关闭该应用程序。但有时 WCF 方法永远不会到达服务器端。
我在客户端和服务器端都有日志,告诉我请求何时发出并完成。大多数时候它运行良好,我可以看到客户端的请求到达服务器,然后应用程序退出。但有时我只能看到客户端发出请求而从未到达服务器。
我认为问题可能是在 Windows 关闭过程中,有时来自 WPF 应用程序的 WCF 请求是在网络连接已关闭时发出的。难道是这个原因吗?如果是的话,有什么解决方法吗?
谢谢
I have a WPF Application that on Windows Shutdown (System.Windows.Application.Current.SessionEnding event) calls a WCF method asynchronously and then the application is closed. But sometimes the WCF method never reaches the server side.
I have logs on both client and server side that tells me when the request is made and completed. Most of the times it works well, i can see the client's request reaching the server and then the application exits. But sometimes i can only see the client making the request and never reaching the server.
I think the issue could be that in the process of windows shutting down, sometimes the WCF request from my WPF application is made when the network connection is already off. Could this be the reason? If it is, is there some workaround?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您异步进行调用,那么它会在后台线程上发生。
后台线程无法阻止应用程序关闭,并且会在应用程序关闭时终止。可能发生的情况是,操作系统告诉您的应用程序它正在关闭 PC,您的应用程序尝试发出异步请求,但未能成功,因为发出请求的后台线程在应用程序关闭时被终止。这不一定会一直发生,但肯定会发生,因为没有任何东西可以确保线程保持活动状态。
您应该做的是显式创建一个新线程并使用它来同步调用您的服务。通过手动创建线程可以将其设置为前台线程;前台线程在完成之前不允许应用程序关闭。所以:
If you're making the call Asyncronously then it's happening on a background thread.
Background threads cannot stop the application closing and are terminated when the app closes. What may be happening is that the OS tells your app that it's shutting down the PC, your app tries to make its Async request but doesn't manage to do so because the background thread that is making it is killed as the app shuts down. This won't necessarily happen all the time but will definitely happen because there's nothing there to ensure that the thread is kept alive.
What you should do is explicitly create a new thread and use this to call your service syncronously. By manually creating a thread you can set it to be a foreground thread; foreground threads won't allow an app to shutdown until they're completed. so: