Hay*_*tam 4 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
});
}
Run Code Online (Sandbox Code Playgroud)
现在我知道Task就像一个新线程,我只是想知道,这对我的软件有害吗?还有其他可能更好的方法吗?
该方法将被执行很多,所以我不知道这种方法是好还是坏
你不应该为此创建一个新任务,你可以改为将方法设为Task,如下所示:
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
}
Run Code Online (Sandbox Code Playgroud)
然后简单地使用它:
public async void Butto1_Click(object sender, EventArgs e)
{
await PerformAction(() => MessageBox.Show("Hello world"), 500);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
85 次 |
| 最近记录: |