Reputation: 39384
I have the following extension method:
public static void With<T>(this T value, Action<T> action);
Which I use as follows:
someT.With(x => { /* Do something with x */ })
How can I apply condition to action execution? Something like:
someT.With(x => { /* if (condiction) stopAction */ })
Is this possible?
Upvotes: 0
Views: 2341
Reputation: 33526
Think about it - where would your action get the condition
from? You have to either provide it as an additional parameter, or catch it in the action's closure (if any, at all). Or, if the action is a normal delegate pointing to some Object.Method, then you could use any fields/properties as conditions, but that's just typical method implementation..
(A)
someT.With( (x,stopConditionHolder) => { while(!stopConditionHolder.StopNow) dosomething; });
// of course, now With() has to get the holder object from somewhere..
(B)
var stopConditionHolder = new ... ();
stopConditionHolder.StopNow = false;
someT.With( (x,stopNow) => { while(!stopConditionHolder.StopNow) dosomething; });
// now you can use the holder object to 'abort' at any time
stopConditionHolder.StopNow = true; // puff!
(C)
class MyAction
{
public bool stopNow = false;
public void PerformSomething()
{
while(!stopNow)
dosomething;
}
}
var actionObj = new MyAction();
someT.With( actionObj.PerformSomething );
// note the syntax: the PerformSomething is PASSED, not called with ().
// now you can use the holder object to 'abort' at any time
actionObj.stopNow = true; // puff!
Also, you might want to look at the framework's CancellationToken
class that is exactly created for that kind of "interruption". The CancellationToken
is the "standard StopNow holder" that you can pass around into opeartions and then asynchronouly order them to abort. Of course, the "operations" have to check upon that token from time to time, just like I did in while(!stop).
Also, if you want to "harshly" abort something, especially when that thing is not "prepared to be cancelled", you might want to check:
However, both of these will require you to have precise access to the worker thread that has "hung". This is often not possible.
Upvotes: 2
Reputation: 4477
I'm assuming here that you are asking to prematurely interrupt an action that you previously started, as your question is not completely clear.
I don't think there's any built in way to do this. If you execute your action on a separate thread, you could abort the thread, but you should probably avoid this.
Alternatively, you would have to create a customized action that performs discrete steps in a loop, and after each step, checks to see whether it has been aborted or not.
Upvotes: 0