C# 停止操作执行

C# 停止操作执行,c#,delegates,extension-methods,C#,Delegates,Extension Methods,我有以下扩展方法: public static void With<T>(this T value, Action<T> action); 如何将条件应用于操作执行?比如: someT.With(x => { /* if (condiction) stopAction */ }) 这可能吗?我在这里假设您要求提前中断您之前开始的操作,因为您的问题并不完全清楚 我不认为有任何内在的方法可以做到这一点。如果在单独的线程上执行操作,可以中止该线程,但可能应该避免这种情

我有以下扩展方法:

public static void With<T>(this T value, Action<T> action);
如何将条件应用于操作执行?比如:

someT.With(x => { /* if (condiction) stopAction */ })

这可能吗?

我在这里假设您要求提前中断您之前开始的操作,因为您的问题并不完全清楚

我不认为有任何内在的方法可以做到这一点。如果在单独的线程上执行操作,可以中止该线程,但可能应该避免这种情况


或者,您必须创建一个自定义操作,该操作在循环中执行离散步骤,并在每个步骤之后检查是否已中止

想一想-你的行为从哪里得到
条件
?您必须将其作为附加参数提供,或者在操作的闭包中捕获它(如果有的话)。或者,如果操作是指向某个Object.Method的普通委托,则可以使用任何字段/属性作为条件,但这只是典型的方法实现

(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!
另外,您可能希望查看框架的
CancellationToken
类,它正是为这种“中断”创建的。
CancellationToken
是“标准的StopNow持有者”,您可以将其传递到操作部分,然后异步命令它们中止。当然,“操作”必须不时地检查该令牌,就像我在while(!stop)中所做的那样

此外,如果您想“严厉”中止某些内容,特别是当该内容未“准备取消”时,您可能需要检查:

  • 在目标线程中引发InterrupedException的中断,它将从任何睡眠/等待中“唤醒”它,但是。。通过从该方法引发异常
  • 引发ThreadAbortException的Thread.Abort-类似地,但更严酷的方式

但是,这两种情况都要求您能够精确访问已“挂起”的工作线程。这通常是不可能的。

您的意思是操作已经开始,并且您想根据某种情况中断它吗?或者你的意思是只有在条件为真时才开始行动?谢谢你的澄清。
(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!