简体   繁体   English

开始,停止,暂停和继续运行很长时间的方法

[英]Start, Stop, Pause and Continue a very long running method

I have a method which is running very long. 我有一个方法正在运行很长时间。 I want to be able to stop, pause and continue the execution of that method.I viewed this question and the answer is nice, but I want to use more general library like TPL. 我希望能够停止,暂停和继续执行该方法。我查看了此问题 ,答案很好,但我想使用更通用的库,例如TPL。 TPL has a cancellation mechanism, but I can't find pause/continue functionality. TPL具有取消机制,但是我找不到暂停/继续功能。

edit 编辑

Thanks for all answers. 感谢所有答案。 But the problem is that I don't write that "long running" method, I just call that method. 但是问题是我不写那种“长时间运行”的方法,我只是调用那个方法。

The easiest way to implement this is with a BackgroundWorker control. 实现此目的最简单的方法是使用BackgroundWorker控件。 It supports cancel and progress reporting. 它支持取消和进度报告。

http://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx http://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx

http://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/48305e65-cea6-4a88-8818-c122e152daa8 http://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/48305e65-cea6-4a88-8818-c122e152daa8

EDIT 编辑

Oh, I see. 哦,我明白了。 Well, there is no "clean" way of pausing and resuming a method that you didn't write, unless you want to suspend the thread. 好吧,除非您想挂起线程,否则没有“干净”的方式来暂停和恢复您未编写的方法。 And, if the method isn't thread-safe, you might be out of luck. 而且,如果该方法不是线程安全的,那么您可能会很不幸。 http://msdn.microsoft.com/en-us/library/d00bd51t.aspx http://msdn.microsoft.com/en-us/library/d00bd51t.aspx

I think you've already answered your own question. 我认为您已经回答了自己的问题。 If you need pause/continue functionality you need to set up some protocol. 如果需要暂停/继续功能,则需要设置一些协议。 As the answer to the question you referenced using reset events is the way to go. 作为您使用重置事件引用的问题的答案,这是要走的路。

If you only need to do Cancel as you said the Task Parallel Library (TPL) has it with the CancelationToken. 如果您只需要按照您所说的那样执行取消,则任务并行库(TPL)会将其与CancelationToken一起使用。

如果时间很长并且需要持久保存,则可能需要查看Windows Workflow Foundation。

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

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