C#计时器无法启动?

时间:2015-03-16 11:20:30

标签: c# timer

我不确定出了什么问题,我编写了一个计时器来延迟一段代码,但它只是没有启动。希望有人可以告诉我是否与await / async有任何关系。

private async void btnOk_Click(object sender, EventArgs e)
{
    this.close() // closes form to prevent further input; is this why timer failed? 

    // Some codes
    Task<string> task = Task.Run(() => PDF.Merge(PDF.Copy(tblPDFs, Appendix, DestFolder), Appendix, DestFolder));
    string PDFresult = await task;

    timer = new Timer();
    timer.Interval = 1000;

    timer.Tick += new EventHandler((abc, def) =>
    {
        MessageBox.Show("HOORAY!"); //<-- not firing! 
        timer.Stop();
    });

    timer.Start();
}

1 个答案:

答案 0 :(得分:0)

根据@spender的建议,我删除了计时器并使用了Task.Delay(),它起作用了:

private async void btnOk_Click(object sender, EventArgs e)
{
    this.close() // closes form to prevent further input; is this why timer failed? 

    // Some codes
    Task<string> task = Task.Run(() => PDF.Merge(PDF.Copy(tblPDFs, Appendix, DestFolder), Appendix, DestFolder));
    string PDFresult = await task;

    await Task.Delay(1000);
    // Codes you want to do. 
}