0

我有以下扩展方法:

public static void With<T>(this T value, Action<T> action);

我使用如下:

someT.With(x => { /* Do something with x */ })

如何将条件应用于操作执行?就像是:

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

这可能吗?

4

2 回答 2

2

想一想——你的行动从哪里来condition?您必须将其作为附加参数提供,或者在操作的闭包中捕获它(如果有的话)。或者,如果操作是指向某个 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 的 Thread.Interrupt,它将从任何睡眠/等待中“唤醒”它,但是......通过从该方法引发异常
  • 引发 ThreadAbortException 的 Thread.Abort - 类似,但更严厉的方式..

但是,这两者都需要您精确访问“挂起”的工作线程。这通常是不可能的。

于 2013-11-07T12:23:19.047 回答
0

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

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

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

于 2013-11-07T12:21:38.073 回答