延迟API动作

时间:2016-07-05 15:12:51

标签: c# api action delay

我正在为我的软件编写API,它有很多接口,我的软件只是继承了它们 我希望API用户有可能在X毫秒后做一些事情,如下所示:

public void PerformAction(Action action, int delay)
{
   Task.Run(async delegate
   {
       await Task.Delay(delai);
       Form.BeginInvoke(action);
       // I invoke on the Form because I think its better that the action executes in my main thread, which is the same as my form's thread
   });
}

现在我知道Task就像一个新线程,我只是想知道,这对我的软件有害吗?还有其他更好的方法吗?
该方法将被执行很多,所以我不知道这种方法是好还是坏

2 个答案:

答案 0 :(得分:6)

您不应该为此创建新任务,而是可以将方法设为任务,如下所示:

public async Task PerformAction(Action action, int delay)
{
   await Task.Delay(delay);
   action(); //this way you don't have to invoke the UI thread since you are already on it
}

然后简单地使用它:

public async void Butto1_Click(object sender, EventArgs e)
{
    await PerformAction(() => MessageBox.Show("Hello world"), 500);
}

答案 1 :(得分:0)

    public async Task PerformAction(Action action, int delay)
    {
        await Task.Delay(delay);
        action();
    }