C# 如何编写可中止的同步方法?

C# 如何编写可中止的同步方法?,c#,multithreading,.net-3.5,asynchronous,C#,Multithreading,.net 3.5,Asynchronous,我需要同步运行方法列表,并能够停止执行列表。在使用重置事件执行之前,很容易停止循环(请参阅Execute中的第一行) 如何同时等待来自action.Execute()和action.Execute()的响应 private ManualResetEvent _abortingToken = new ManualResetEvent(false); private List<IAction> _actions; public void Abort() { _abortingT

我需要同步运行方法列表,并能够停止执行列表。在使用重置事件执行之前,很容易停止循环(请参阅
Execute
中的第一行)

如何同时等待来自
action.Execute()
action.Execute()
的响应

private ManualResetEvent _abortingToken = new ManualResetEvent(false);
private List<IAction> _actions;

public void Abort()
{
    _abortingToken.Set();
}

public void Execute()
{
    foreach (var action in _actions)
    {
        if (_abortingToken.WaitOne(0))
            break; // Execution aborted.

        action.Execute(); // Somehow, I need to call this without blocking

        while (/*Execute not finished*/)
        {
            if (_abortingToken.WaitOne(1))
                action.Abort();
        }
    }
}

这与同步性相反。
您需要在后台线程上运行该方法


例如,您可以使用
Delegate.BeginInvoke
调用该方法,然后选中
IAsyncResult.IsCompleted
。(并确保之后调用
EndInvoke

您可以在另一个线程中运行Execute,然后您的while尝试加入超时

public void Execute()
{
    foreach (var action in _actions)
    {
        if (_abortingToken.WaitOne(0))
            break; // Execution aborted.

        var workThread = new Thread(action.Execute); 
        workThread.Start();

        while (!workThread.Join(100)) /Milliseconds, there is also a timespan overload
        {
            if (_abortingToken.WaitOne(1))
                action.Abort();
        }
    }
}

请参阅。

谢谢。使用
BeginInvoke
创建一个非常优雅的代码,而不会产生大量开销。但是我必须调用
EndInvoke
EndInvoke
的唯一目的不是检索返回值或异常吗?如果我不关心结果怎么办(即中止后)?@HuBeZa:如果你不调用
EndInvoke
,你会泄漏内存。
public void Execute()
{
    foreach (var action in _actions)
    {
        if (_abortingToken.WaitOne(0))
            break; // Execution aborted.

        var workThread = new Thread(action.Execute); 
        workThread.Start();

        while (!workThread.Join(100)) /Milliseconds, there is also a timespan overload
        {
            if (_abortingToken.WaitOne(1))
                action.Abort();
        }
    }
}