使用计时器取消并重新启动异步任务

时间:2019-05-31 13:43:47

标签: c# asynchronous timer task cancellation-token

我从异步编程开始。我想每5分钟运行一次任务,我可以取消并重新启动此任务。

下面的代码指的是我的想象,但是到目前为止,我不知道它是否正确。我的问题是如何实施取消和重新启动。

public partial class Form1 : Form
{
    private readonly SynchronizationContext _synchronizationContext;

    public Form1()
    {
        InitializeComponent();
        _synchronizationContext = SynchronizationContext.Current;
    }

    // Start
    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            Task.Run(async () =>
            {
                while (true)
                {
                    try
                    {
                        await Method1();
                        await Method2();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                    await Task.Delay(TimeSpan.FromMinutes(5));
                }
            });
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

    // Stop
    private void button2_Click(object sender, EventArgs e)
    {
        try
        {
            // I would like to call here the cancellation of the task.
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

    // Method 1
    private async Task Method1()
    {
        await Task.Delay(1000);
        var now = DateTime.Now;
        _synchronizationContext.Post(new SendOrPostCallback(o =>
        {
            richTextBox1.AppendText(string.Format("Finalização do método 1: {0:hh:mm:ss}{1}", o, Environment.NewLine));
        }), now);
    }

    // Method 2
    private async Task Method2()
    {
        await Task.Delay(1000);
        var now = DateTime.Now;
        _synchronizationContext.Post(new SendOrPostCallback(o =>
        {
            richTextBox1.AppendText(string.Format("Finalização do método 2: {0:hh:mm:ss}{1}", o, Environment.NewLine));
        }), now);
    }
}

有人可以帮助我检查这是否是每5分钟执行一次任务的正确方法,还是还有另一种方法?我还需要取消和重新启动此任务的帮助。

谢谢!

0 个答案:

没有答案