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

时间:2015-01-05 16:54:41

标签: c# wpf .net-4.0

我在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;
}

有任何线索吗?

2 个答案:

答案 0 :(得分:3)

使用.NET任务,你可以做这样的事情。

1-首先解决并运行任务

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

2-这样称呼它

await this.ExecuteTask(result);

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

答案 1 :(得分:0)

最后我发现了以下内容:

  1. 我得到的代码是正确的,并且100%异步工作。
  2. 我面临的问题是因为第二种方法SendEmail(userId,entityId);需要时间才能执行,因此第一种方法的触发时间要晚于它应该。
  3. 所以我找到了一个有效的解决方案。

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