我正在为我的软件编写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
});
}
现在我知道任务就像一个新的线程,但我想知道这对我的软件有没有不好的影响?是否有其他更好的方式?
这个方法会被频繁执行,所以我不知道这种方法是好还是坏。
PerformAction
改成async Task
,然后只需调用await Task.Delay(); action();
就可以了?启动一个任务只是为了让它睡眠,然后尝试回到UI线程非常复杂。 - Panagiotis Kanavos