Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 延迟API操作_C#_Api_Action_Delay - Fatal编程技术网

C# 延迟API操作

C# 延迟API操作,c#,api,action,delay,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

我正在为我的软件编写一个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);
}
然后像这样简单地使用它:

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);
}

为什么不简单地将
性能
更改为
异步任务
,然后调用
wait Task.Delay();动作()?启动一个任务只是为了让它休眠,然后尝试返回UI线程是非常复杂的,因为我需要API用户像这样使用它:Client.performation(TheirAction,1000);因为并不是每个用户都知道tasks/async的用法,因为框架本身充满了异步方法。如果您不了解任务,就不能对.NET进行编程
async void
是一个非常糟糕的主意,因为它不能等待,也不能处理异常。它应该只用于事件处理程序(或具有fire-and-forget语义的类似方法)@PanagiotisKanavos基本同意,但是,在UI事件中使用它是可以的。Cfrozendath有一个更好的答案。不,不好。您的代码可能永远不会触发,或者
action()
可能会抛出并未被检测到。@PanagiotisKanavos您是对的。后更新。你能取消否决票吗?如果他们在他们创建的新线程上执行该方法怎么办?@HaitamZanid在这种情况下,你需要先调用UI线程。您还可以解释如何使用API,并让API的用户在面对异常时阅读它。o Form.BeginInvoke(action);这是个坏主意吗?@HaitamZanid这不是个坏主意,只是如果API使用正确的话就多余了。当然,这仅在操作将与UI对象交互时才需要。如果该操作不使用UI对象,那么就不需要调用UI线程,因为我的软件不适用于c#级别较高的用户,这就是为什么我更喜欢处理一些异常以使其变得简单^^