延迟 API 行动
Delaying API actions
我正在为我的软件编写 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
});
}
现在我知道任务就像一个新的线程,我只想知道,这对我的软件有害吗?还有其他更好的方法吗?
该方法会执行很多,所以我不知道这种方法是好是坏
public async Task PerformAction(Action action, int delay)
{
await Task.Delay(delay);
action();
}
你不应该为此创建一个新的任务,你可以将这个方法变成一个任务,像这样:
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);
}
我正在为我的软件编写 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
});
}
现在我知道任务就像一个新的线程,我只想知道,这对我的软件有害吗?还有其他更好的方法吗?
该方法会执行很多,所以我不知道这种方法是好是坏
public async Task PerformAction(Action action, int delay)
{
await Task.Delay(delay);
action();
}
你不应该为此创建一个新的任务,你可以将这个方法变成一个任务,像这样:
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);
}