Share via

c# question regarding calling async function

T.Zacks 3,996 Reputation points
2022-08-30T07:26:14.547+00:00

see the code first from attached text file.236013-async-code.txt

i am waiting 10 sec for async function and waiting 2 sec for sync function.

in my above function async function start and sync function start and end and at the end async function end which is expected.

if i do not call async function above way instead if i call it below way then i am not getting expected result.

        static async void Test()  
        {  
            SynchronousTask();  
            int intResult = await GetTaskOfTResultAsync();  
            Console.WriteLine("GetTaskOfTResultAsync result " + intResult);  
        }  

OR

        static async void Test()  
        {  
            int intResult = await GetTaskOfTResultAsync();  
            SynchronousTask();  
            Console.WriteLine("GetTaskOfTResultAsync result " + intResult);  
        }  
  

if i want to get desired output then i have assign async task to variable and later await that variable like this way

            Task<int> returnedTaskTResult = GetTaskOfTResultAsync();  
            SynchronousTask();  
            int intResult = await returnedTaskTResult;  

how can i change my code where i will just await my async function directly which would call async function first but thread will not be blocked and sync function will be called.

please advise. thanks

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.


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.