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

标签 c# multithreading .net-3.5 asynchronous

我需要同步运行一个方法列表,并能够停止执行列表。在执行之前使用重置事件很容易停止循环(请参阅 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();
        }
    }
}

我认为使用 Tasks 进行预成型很容易,但不幸的是我使用的是 .net 3.5。


编辑解决方案灵感来自 SLaks answer :

public void Execute()
{
    Action execute = null;
    IAsyncResult result = null;

    foreach (var action in _actions)
    {
        execute = new Action(scriptCommand.Execute);

        if (_abortingToken.WaitOne(0))
            break; // Execution aborted.

        result = execute.BeginInvoke(null, null);

        while (!result.IsCompleted)
        {
            if (_abortingToken.WaitOne(10))
            {
                action.Abort();
                break;
            }
        }

        execute.EndInvoke(result);
    }
}

最佳答案

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

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

关于c# - 如何编写可中止的同步方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4984732/

相关文章:

c# - 单个 C# 类的多个枚举器

php - “Serialization of '在Symfony应用程序中调用\Threaded类(pthread)时关闭' is not allowed”

Python:os.read()/os.write() 在 os.pipe() 线程安全吗?

java - 了解 Java 中同步块(synchronized block)与 volatile 变量的原子性、可见性和重新排序

c# - 在 C# 中发送电子邮件

c# - 从 TextBox 获取 .Text 值

javascript - 如何在 Neutronium 库中执行 javascript?

c# - DateTime.UtcNow 会在同一个方法中返回不同的值吗?

c# - 值注入(inject)器和数据表

orm - 使用 dot net 3.5 的 dapper dot net 的 CRUD