I'm designing a plugin system for my app.
there is a "Start" button in UI. When user clicks on it, app should call a method in plugin dll asynchronously and change "Start" to "Stop". That method could include almost anything as it is for plugin. When user clicks "Stop", that asynchronous method should be terminated immediately.
I wanted to use Thread.Abort();
but everyone recommends not to use it. If I use CancellationTokenSource, I have to add cancellation handling to all plugins and I prefer not to do this.
I need something like a force shutdown, unplug or destroy (if needed!) for a PC. The only important thing for me is immediate stop. No cleanup or things like this are needed as my app unloads the plugin after using it and plugins have nothing to do with main app codes.
Isn't there anyway to start a method asynchronously and have full control on it? Is it OK to use Thread.Abort();
in this situation (if I guarantee the dll won't catch thread abort exception)?
EDIT: Is there any way to actively monitor cancellation token in plugin dll (class) asynchronously while running method and kill method when requested?
EDIT2: I think it is not a good idea but what about creating a new process and use Process.kill()
?
No, I'm afraid you have to use an extra parameter for the cancellation token.
Avoid working with threads as they are pretty low-level and try to use the utilities and abstractions of Tasks, which hide much of the hassle.
Edit: You mention in your answer and in your comments that you want to cancel an asynchronous method, but you also mention this not to be a Task. This baffles me. Let's say you have a class where you handle the Start / Stop code.
- Start
When you want to start the asynchronous processing of your plugin, you will have to create a new CancellationTokenSource()
, and hold it as a private variable in the class that controls the Start/Stop.
Let's say now that you now have a method that you want to run asynchronously, and it has the signature:
public Task Run(string anyArgument)
.
You should also add another argument, so it becomes:
public Task Run(string anyArgument, CancellationToken token)
Most libraries that expose asynchronous methods also accept an optional parameter for the CancellationToken. The logic behind this is that when (from any place) you want the process cancelled, you request the token to stop, and in its turn it will stop any asynchronous operation, if it's checked.
Having said that, let's go to...
- Stop
If you want to stop the operation, you will simply use the CancellationTokenSource that you initialized in the Start
method, and will call cts.Cancel()
More information about handling of CancellationTokens you can find in the documentation or in this SO question
Also check: