gpt4 book ai didi

c# - 延迟 API 操作

转载 作者:太空狗 更新时间:2023-10-30 00:49:25 24 4
gpt4 key购买 nike

我正在为我的软件编写一个 API,它有很多接口(interface),我的软件只是继承了它们。
我希望 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(); //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);
}

关于c# - 延迟 API 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38207019/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com