使用外部事件打破一个循环

8 .net c# state-machine workflow-foundation while-loop

我在Windows服务中有一个while循环,运行x次,并在从某个文件中读取后启动x电话.现在,如果我想创建一个用户界面,它提供了一个停止电话呼叫的选项,即在完成之前打破while循环.我该怎么办?

让我们假设我有一个功能.

DialCalls(x)
{
  for(int i= 0 ; i<x ; i++)
  {
    // Initiate call
  }
}
Run Code Online (Sandbox Code Playgroud)

可以在不同的线程中同时运行2,3个DialCalls函数,因为我在应用程序中也进行了线程处理.所以基本上什么是打破网页循环的最佳方法.

Joh*_*son 6

使用任务取消(.net 4中的新功能):

[Fact]
public void StartAndCancel()
{
    var cancellationTokenSource = new CancellationTokenSource();
    var token = cancellationTokenSource.Token;
    var tasks = Enumerable.Repeat(0, 2)
                          .Select(i => Task.Run(() => Dial(token), token))
                          .ToArray(); // start dialing on two threads
    Thread.Sleep(200); // give the tasks time to start
    cancellationTokenSource.Cancel();
    Assert.Throws<AggregateException>(() => Task.WaitAll(tasks));
    Assert.True(tasks.All(t => t.Status == TaskStatus.Canceled));
}

public void Dial(CancellationToken token)
{
    while (true)
    {
        token.ThrowIfCancellationRequested();
        Console.WriteLine("Called from thread {0}", Thread.CurrentThread.ManagedThreadId);
        Thread.Sleep(50);
    }
}
Run Code Online (Sandbox Code Playgroud)

http://blogs.msdn.com/b/csharpfaq/archive/2010/07/19/parallel-programming-task-cancellation.aspx 任务吞下异常,所以有一些清理,可能是IDisposable? 关于任务例外