C#定时功能

时间:2015-02-23 11:33:18

标签: c# wpf multithreading asynchronous timer

我有以下问题:

我需要运行一个函数搜索(深度x),它基本上搜索决策树直到某个深度,然后返回(或在类成员中留下)Move类型的值。与此同时,我希望能够“取消”搜索的执行,如果它持续太久。

如果搜索确实更快完成,我也不必等待它也很重要。我意识到这并不复杂,但我并不熟悉C#并发控制。

2 个答案:

答案 0 :(得分:0)

这是一个简单的例子作为起点:

public class Runner
{
    private Task<int> search(CancellationToken ct)
    {
        var t_work = Task.Factory.StartNew<int>(() =>
        {
            int k = 0;

            while (k < 1000)
            {
                if (ct.IsCancellationRequested)
                {
                    return -1;
                }                    
                k += r.Next(200);
                Thread.Sleep(300);
            }
            return k;

        }, ct);
        return t_work;
    }

    Random r = new Random();

    public async Task SearchAsync()
    {
        var timeout = TimeSpan.FromSeconds(3);
        var cts = new CancellationTokenSource(timeout);
        var ct = cts.Token;
        var searchValue = await search(ct);
        string result = (searchValue < 0) ?
            "Search aborted without results" : "search value is: " + searchValue.ToString();
        Console.WriteLine(result);
    }
}

你可以在这样的控制台应用中使用它:

Console.WriteLine("test");
var r = new Runner();
r.SearchAsync().Wait();
r.SearchAsync().Wait();
r.SearchAsync().Wait();
r.SearchAsync().Wait();
Console.WriteLine("done..");

答案 1 :(得分:0)

我会使用Task,因为它内置了在任务完成时处理错误,取消和运行Continuation Tasks的机制。

假设我认为您在自己的问题中隐含了自定义返回类型的Move:

private Task<Move> _searchTask;
private CancellationTokenSource _searchCancellationTokenSrc;

然后点击按钮或类似按钮,启动任务。这将立即返回,保持您的UI响应:

private void StartButton_Click(object sender, RoutedEventArgs e)
{
    _searchCancellationTokenSrc = new CancellationTokenSource();
    CancellationToken ct = _searchCancellationTokenSrc.Token;

    _searchTask = Task.Run(() =>
    {
         for (int i = 0; i < 10; i++ )
         {
             if(ct.IsCancellationRequested)
             {
                 // Clean up here
                 ct.ThrowIfCancellationRequested();
             }
             // Time consuming processing here
             Thread.Sleep(1000);
         }
         return new Move();
    },ct);

    _searchTask.ContinueWith((t) =>
    {
         Console.WriteLine("Canceled");
    }, TaskContinuationOptions.OnlyOnCanceled);

    _searchTask.ContinueWith((t) =>
    {
       Console.WriteLine("Faulted. t.Exception contains details of any exceptions thrown");               
    }, TaskContinuationOptions.OnlyOnFaulted);

    _searchTask.ContinueWith((t) =>
    {            
        Console.WriteLine("Completed t.Result contains your Move object");
    }, TaskContinuationOptions.OnlyOnRanToCompletion);
}

要取消此操作,可能是从另一个按钮取消:

 private void CancelButton_Click(object sender, RoutedEventArgs e)
 {
      _searchCancellationTokenSrc.Cancel();
 }