【发布时间】:2011-06-26 11:09:01
【问题描述】:
我需要同步运行一个方法列表,并能够停止执行列表。在执行之前使用重置事件很容易停止循环(参见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);
}
}
【问题讨论】:
标签: c# multithreading .net-3.5 asynchronous