Skip to main content
 首页 » 编程设计

c#之如何在 .net 4 中异步执行 Action

2024年08月06日35sxdcgaq8080

我在 WPF 应用程序中得到了这段代码。

public void NotifyEntityUpdated(int userId, int entityId) 
{ 
   Action currentAction = () => 
   { 
      EntityUpdatedByUser(userId, entityId); 
      SendEmail(userId, entityId); 
   }; 
   this.Dispatcher.BeginInvoke(currentAction); 
} 

我如何在 .net 4 中异步执行它?

据我所知,我不能像这样使用 async/await...

public async Task<T> DoSomethingAsync<T>(Func<T, Task> resultBody) where T : Result, new() 
{ 
    T result = new T(); 
    await resultBody(result); 
    return result; 
} 

有什么线索吗?

请您参考如下方法:

使用 .NET 任务,您可以执行类似的操作。

1-首先解决并运行任务

private Task ExecuteTask(Result result) 
{ 
  return Task.Run(() => 
  { 
     this.resultBody(result) 
  }); 
} 

2-这样调用它

await this.ExecuteTask(result); 

//我这里没有 VS,但我希望它能用,祝你好运!