如何仅在Windows服务完成时继续执行代码?
我有一个 Windows 服务,它执行相当长的运行任务。目前,我生成一个新线程,该线程执行一个方法,该方法会关闭并调用此 Windows 服务。此代码如下所示:
Thread thread = new Thread(new ThreadStart(ExecyuteLongRunningMethod));
thread.Start();
thread.Join();
在调用堆栈的较高位置(当此代码完成时),会弹出一个消息框,说明操作的结果。
但是,当执行此代码块时(ExecuteLongRunningMethod
调用 Windows svc),会弹出一个消息框,指出操作结果没有任何更改,但因为这是在上面的代码块完成之前,出现错误消息框。
因此,问题是,仅当 Windows 服务完成时,仅在 winforms 应用程序(这就是所谓的 windows svc)中继续执行的正确方法是什么?我认为上面的方法是不正确的,因为线程将调用 Windows 服务(另一个进程),因此当 Windows 服务执行其操作时,我的代码(winforms 应用程序)将继续。要么需要某种信号,要么需要诸如命名管道之类的东西?
该应用程序采用 .NET 3.5。
谢谢
I have a Windows service which performs a fairly long running task. At the moment, I spawn a new thread, which executes a method which goes off and calls this windows service. This code looks like:
Thread thread = new Thread(new ThreadStart(ExecyuteLongRunningMethod));
thread.Start();
thread.Join();
Higher up in the callstack (when this code is done), a message box popups stating the result of the operation.
However, while this block of code executes (ExecuteLongRunningMethod
calls the windows svc), a message box popups stating that nothing has changed as a result of the operation, but because this is before the code block above has completed, the wrong message box appears.
Thus, the question is, what would be the proper way to only continue execution in the winforms app (this is what calls the windows svc), ONLY when the windows service is finished? I am thinking that the approach above is incorrect as the thread will call the windows service (another process), so while the windows service does its stuff, my code (winforms app) will continue. Either some sort of signaling is required, or something like named pipes?
The app is in .NET 3.5.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通过 WCF API 公开服务执行的状态并使用 netTcp 或命名管道调用它,您可以轮询服务或使用 WCF 回调。
Expose the status of your service execution via a WCF API and call it using netTcp or named pipes, you could poll the service or use a WCF CallBack.
为什么不使用BackgroundWorker,这样你就可以设置一个事件来完成它?
在Backgroundworker运行方法中,您可以运行服务并等待手动重置事件(例如)或互斥体,当收到此事件时,您可以退出主方法。
因此,OnCompleted 事件会在您的主线程(例如 UI)中引发,并且工作已完成...
在您的应用中添加一个 Backgroundworker 并将其命名为
bgw
。然后你可以这样做:
Why don't you use a BackgroundWorker, so you can set an event for its completion?
In Backgroundworker running method you can run the service and wait for a manual reset event (for example) or a mutex and, when received this you can exit main method.
So OnCompleted event is raised in your main thread (UI for example) and the job is done...
In your app add a Backgroundworker and name it
bgw
.Then you can do: