0
votes

I guess I could run method that uses 'async Task' method asynchronously after I call it, but it blocked, actually it runs synchronously,see my code like below.

    static void Main(string[] args)
    {
        asyncTest();// use asyncTest.Wait() help nothing. 
        Console.ReadKey();
    }

    static async Task asyncTest() 
    {
        Console.WriteLine("before init task second " + DateTime.Now.Second);
        var t1 = getInt1S();// I supposed it to run background,but it blocked
        var t3 = getInt3S();
        //var await1 = await t1;//this line just no use, run quickly
        //var await3 = await t3;//this line just no use, run quickly
        Console.WriteLine("after init task second " + DateTime.Now.Second);
    }

    static async Task<int> getInt1S() 
    {
        Console.WriteLine("getInt1S" + DateTime.Now.Second);
        Task.Delay(1000).Wait();
        return 1;
    }

    static async Task<int> getInt3S() 
    {
        Console.WriteLine("getInt3S" + DateTime.Now.Second);
        Thread.Sleep(3000);
        return 3;
    }

output like:

before init task second 21
getInt1S 21
getInt3S 22
after init task second 25

why does 'getInt1S()' and 'await getInt3S()' all run synchronously? Is there any way to code like :

var a = methodSync();//method define like: async Task<T> methodSync()
Console.Write("");//do something during processing the methodSync
T b = await a;

I'm not going to find out how to use 'async methodSync()' in ConsoleApp.Just how to make my 't1' and 't2' run asynchronously in 'asyncTest()'.

I'm working on async/await,so I want find something differ from ' var a = new Task(()=>{return 1;}) '

Do the way of call asyncTest() matter? or anything I missed?

Anyone who could help me out? or point out my error.

Thanks.

1
The compiler will give you warnings telling you that your async methods will run synchronously because you do not use await. I have an async tutorial that you may find helpful. - Stephen Cleary

1 Answers

2
votes

All asynchronous methods run synchronously up until the first await instruction.

Then, if the awaitable (what await awaits on) is completed, it will continue running synchronously up until the next await instruction or the end of the method.

As soon as a not completed awaitable is reached, the control is returned to the calling method returning a Task that will complete when all awaitables in the asynchronous method are completed and the end of the method is reached.

The intent of this compiler feature is to easily produce code that runs sequentially (not synchronously), thus, what you are seeing.