Task.Delay没有被取消?

时间:2018-07-02 07:13:03

标签: c# task-parallel-library cancellation cancellationtokensource

我正在尝试为游戏构建界面。游戏运行1分钟。 GetStop 方法在游戏60秒后停止。 方法开始游戏,退出方法退出游戏。现在理想情况下,我想要的是30秒后退出游戏时,计时器应重置,并单击“播放”按钮,计时器应再次运行1分钟。这样下一场比赛就会持续1分钟。如果我再次按退出按钮,则应该为下一场比赛重置计时器。

但是,我的代码似乎存在某些问题。每当我执行quit方法时,计时器似乎都保存在该状态。因此,如果我在30秒内退出比赛,那么下一场比赛将仅持续30秒。如果我在50秒内退出比赛,下一场比赛将仅持续10秒。理想情况下,计时器应该重置,但不重置。

我在这里没主意。谁能提供一些建议吗?

private async Task GetStop(CancellationToken token)
{ 
    await Task.Run(async () =>
    {
        token.ThrowIfCancellationRequested();
        await Task.Delay(TimeSpan.FromSeconds(60), token);

        token.ThrowIfCancellationRequested();
        if (!token.IsCancellationRequested)
        {
            sendMessage((byte)ACMessage.AC_ESCAPE); 
        }
    }, token);
}

public async void Play()
{         
        sendMessage((byte)ACMessage.AC_START_RACE); 
        _cts.Cancel();

        if (_cts != null)
        {
            _cts.Dispose();
            _cts = null;
        }
        _cts = new CancellationTokenSource(); 
        await GetStop(_cts.Token);
   }

public void Quit()
{
        _cts.Cancel();
        if (_cts != null)
        {
            _cts.Dispose();
            _cts = null;
        }
    //
}

2 个答案:

答案 0 :(得分:1)

我可以看到您的代码可能在多个地方引发异常。 如果您正在捕获并忽略所有异常,则可能无法看到时间,取消令牌和任务无法正常工作的原因。

乍一看,我可以确定以下内容:

private async Task GetStop(CancellationToken token)
{ 
    await Task.Run(async () =>
    {
        // I think you don't need to throw here
        token.ThrowIfCancellationRequested();

        // this will throw an Exception when cancelled
        await Task.Delay(TimeSpan.FromSeconds(60), token); 

        // again, I think you don't need to throw here
        token.ThrowIfCancellationRequested();

        if (!token.IsCancellationRequested)
        {
            sendMessage((byte)ACMessage.AC_ESCAPE); 
        }
    }, token);
}

public async void Play()
{         
        sendMessage((byte)ACMessage.AC_START_RACE); 

        // at some scenarios this may be null
        _cts.Cancel();

        if (_cts != null)
        {
            _cts.Dispose();
            _cts = null;
        }
        _cts = new CancellationTokenSource(); 
        await GetStop(_cts.Token);
   }

public void Quit()
{
        _cts.Cancel();
        if (_cts != null)
        {
            _cts.Dispose();
            _cts = null;
        }
}

我创建了一个控制台应用程序,进行了一些小修改,在这里看来一切正常。请看一下:

public static class Program
{
    public static void Main(string[] args)
    {
        var game = new Game();

        game.Play();
        Task.Delay(5000).Wait();
        game.Quit();

        game.Play();
        Task.Delay(15000).Wait();
        game.Quit();

        game.Play();
        Task.Delay(65000).Wait();

        Console.WriteLine("Main thread finished");
        Console.ReadKey();

        // Output:
        //
        // Start race (-00:00:00.0050018)
        // Quit called (00:00:05.0163131)
        // Timeout (00:00:05.0564685)
        // Start race (00:00:05.0569656)
        // Quit called (00:00:20.0585092)
        // Timeout (00:00:20.1025051)
        // Start race (00:00:20.1030095)
        // Escape (00:01:20.1052507)
        // Main thread finished
    }
}

internal class Game
{
    private CancellationTokenSource _cts;

    // this is just to keep track of the behavior, should be removed
    private DateTime? _first;
    private DateTime First
    {
        get
        {
            if (!_first.HasValue) _first = DateTime.Now;
            return _first.Value;
        }
    }


    private async Task GetStop(CancellationToken token)
    {
        await Task.Run(async () =>
        {
            try
            {
                // we expect an exception here, if it is cancelled
                await Task.Delay(TimeSpan.FromSeconds(60), token);
            }
            catch (Exception)
            {
                Console.WriteLine("Timeout ({0})", DateTime.Now.Subtract(First));
            }

            if (!token.IsCancellationRequested)
            {
                Console.WriteLine("Escape ({0})", DateTime.Now.Subtract(First));
            }
        }, token);
    }

    public async void Play()
    {
        Console.WriteLine("Start race ({0})", DateTime.Now.Subtract(First));

        CancelAndDisposeCts();

        _cts = new CancellationTokenSource();
        await GetStop(_cts.Token);
    }

    public void Quit()
    {
        Console.WriteLine("Quit called ({0})", DateTime.Now.Subtract(First));
        CancelAndDisposeCts();
    }

    private void CancelAndDisposeCts()
    {
        // avoid copy/paste for the same behavior
        if (_cts == null) return;

        _cts.Cancel();
        _cts.Dispose();
        _cts = null;
    }
}

我还建议看一下System.Threading.Timer,也许在某些情况下可能有用...

祝你游戏好运!

答案 1 :(得分:1)

出于我自己的目的,我创建了一个名为CancellableTask的包装,它可以帮助您实现所需的目标。您可以通过将delegate作为参数传递给构造函数来创建任务,然后可以Run进行延迟或不进行延迟。在延迟期间或运行期间,它可以随时为Canceled

这是课程:

public class CancellableTask
    {
        private CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
        private Task cancellationTask = null;
        private Action<Task> method;
        private int delayMilis;

        public bool Delayed { get; private set; }

        public TaskStatus TaskStatus => cancellationTask.Status;

        public CancellableTask(Action<Task> task)
        {
            method = task;
        }

        public bool Cancel()
        {
            if (cancellationTask != null && (cancellationTask.Status == TaskStatus.Running || cancellationTask.Status == TaskStatus.WaitingForActivation))
            {
                cancellationTokenSource.Cancel();
                cancellationTokenSource.Dispose();
                cancellationTokenSource = new CancellationTokenSource();
                return true;
            }
            return false;
        }

        public void Run()
        {
            Delayed = false;
            StartTask();
        }

        public void Run(int delayMiliseconds)
        {
            if(delayMiliseconds < 0)
                throw new ArgumentOutOfRangeException();

            Delayed = true;
            delayMilis = delayMiliseconds;
            StartDelayedTask();
        }

        private void DelayedTask(int delay)
        {
            CancellationToken cancellationToken = cancellationTokenSource.Token;
            try
            {
                cancellationTask =
                    Task.
                        Delay(TimeSpan.FromMilliseconds(delay), cancellationToken).
                        ContinueWith(method, cancellationToken);

                while (true)
                {
                    if (cancellationTask.IsCompleted)
                        break;

                    if (cancellationToken.IsCancellationRequested)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                //handle exception
                return;
            }

        }

        private void NormalTask()
        {
            CancellationToken cancellationToken = cancellationTokenSource.Token;
            try
            {
                cancellationTask =
                    Task.Run(() => method, cancellationToken);

                while (true)
                {
                    if (cancellationTask.IsCompleted)
                        break;

                    if (cancellationToken.IsCancellationRequested)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                //handle exception
                return;
            }
        }

        private void StartTask()
        {
            Task.Run(() => NormalTask());
        }

        private void StartDelayedTask()
        {
            Task.Run(() => DelayedTask(delayMilis));
        }

    }

它可以像这样使用:

var task = new CancellableTask(delegate
            {
               DoSomething(); // your function to execute
            });
task.Run(); // without delay
task.Run(5000); // with delay in miliseconds
task.Cancel(); // cancelling the task