问题
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 has a cancellation mechanism, but I can't find pause/continue functionality.
edit
Thanks for all answers. But the problem is that I don't write that "long running" method, I just call that method.
回答1:
The easiest way to implement this is with a BackgroundWorker control. It supports cancel and progress reporting.
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
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
回答2:
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.
回答3:
If it is very long and needs to be persistent you might want to have a look at Windows Workflow Foundation.
来源:https://stackoverflow.com/questions/5506457/start-stop-pause-and-continue-a-very-long-running-method