NoWar
NoWar

Reputation: 37633

How to execute Action asynchronously in .net 4

I have got this code in WPF application.

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

How I can execute it asynchronously in .net 4?

As I see I cannot use async/await like this...

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

Any clue?

Upvotes: 1

Views: 836

Answers (2)

NoWar
NoWar

Reputation: 37633

Finally I found the following:

  1. The code I have got is correct and work asynchronously 100%.
  2. The issue I am facing happening because second method SendEmail(userId, entityId); is taking time to be executed so the first method is firing later than it should.

So I found a working solution.

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

Upvotes: 0

MrVoid
MrVoid

Reputation: 709

Using the .NET Task's you can do something like this.

1- First resolve and run the task

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

2- Call it like this

await this.ExecuteTask(result);

// I dont have the VS here but I hope it will work ,good luck!

Upvotes: 3

Related Questions