How to asynchronously wait for x seconds and execute something then?

前端 未结 8 875
深忆病人
深忆病人 2020-12-03 03:03

I know there is Thread.Sleep and System.Windows.Forms.Timer and Monitor.Wait in C# and Windows Forms. I just can\'t seem to be able to figure out how to wait fo

8条回答
  •  盖世英雄少女心
    2020-12-03 03:26

    You can start an asynchronous task that performs your action:

    Task.Factory.StartNew(()=>
    {
        Thread.Sleep(5000);
        form.Invoke(new Action(()=>DoSomething()));
    });
    

    [EDIT]

    To pass the interval in you simply have to store it in a variable:

    int interval = 5000;
    Task.Factory.StartNew(()=>
    {
        Thread.Sleep(interval);
        form.Invoke(new Action(()=>DoSomething()));
    });
    

    [/EDIT]

提交回复
热议问题