Share via

Asynchronous Task

Ronald Rex 1,671 Reputation points
2023-08-17T16:57:09.71+00:00

Hi Friends. I am trying to run an asyncronous Task like the one below but it only executes the one line Purchasing as seen in the jpg image. It should execute the rest of the code in the Task. I also received the warning...The current method calls an async method that returns a Task or a Task<TResult> and doesn't apply the await operator to the result. The call to the async method starts an asynchronous task. However, because no await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't what you expect. Usually other aspects of the calling method depend on the results of the call or, minimally, the called method is expected to complete before you return from the method that contains the call.

 public  async Task MakePurchase(PurchaseMessenger messenger, PurchaseMessenger messenger2)
        {
            Console.WriteLine("Purchasing...");
            await Task.Delay(2000);

           Console.WriteLine("Sorry for the delay...\n");
            //messenger points to NotifyPurchase()
            messenger();

            //messenger2 points to NotifyPerson()
            messenger2();
        }


AsyncIssue.JPG

Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


Answer accepted by question author

Bruce (SqlWork.com) 84,086 Reputation points
2023-08-17T17:45:07.97+00:00

when the caller calls MakePurchase() it returns a task when it execute the first await. if the caller of MakePurchase() does not use await, continuation routine or .Wait() then it will not know when the task completed.

var task = MakePurchase(...);
dosomething1(); // MakePurchase has not called messenger yet
dosomething2(); // unknown state
task.Wait();   // will block thread until task completed calling messenger2()

Was this answer helpful?

1 person found this answer helpful.
0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.