简体   繁体   中英

the part of code before and after await task is executed in same thread

i have the following code in my Console Application Project :

static void Main()
{
    Console.WriteLine($@"{Thread.CurrentThread.ManagedThreadId}, main");
    var list = new List<Task<int>>();
    for (int i = 1; i < 4; i++)
    {
        list.Add(GetValueAsync(i, i, i));
        //list.Add(GetValueAsync());
    }

    var whenAll = Task.WhenAll(list);
    whenAll.Wait();

    Console.WriteLine(@"End program");
    Console.ReadLine();
}


private static async Task<int> GetValueAsync(int val, int delay, int taskId)
{
    Console.WriteLine($@"{Thread.CurrentThread.ManagedThreadId}, task{taskId} sleep");

    await Task.Delay(1000 * delay);

    Console.WriteLine($@"{Thread.CurrentThread.ManagedThreadId}, task{taskId} awake");
    return val;
}

private static int index = 0;
private static async Task<int> GetValueAsync()
{
    index++;
    Console.WriteLine($@"{Thread.CurrentThread.ManagedThreadId}, task{index} sleep");

    await Task.Delay(2000);

    Console.WriteLine($@"{Thread.CurrentThread.ManagedThreadId}, task{index} awake");
    return 10;
}

when i use GetValueAsync with parameters i get this one :

在此处输入图片说明

when i use GetValueAsync without parameters i get this one :

在此处输入图片说明

Why do the part of code after await Task.Delay(1000 * delay) is executed in the same thread , when i use GetValueAsync(int val, int delay, int taskId) ? if i am not wrong , the part after await supposed to be executed in the new thread... (current project is a console application , the main thread is not GUI thread )

These are always hard questions to answer as the answers never seem satisfying to people new to the topic

If you change your code to the following. you will get the expected results

list.Add(GetValueAsync(i, 1, i));

Output

1, main
1, task1 sleep
1, task2 sleep
1, task3 sleep
5, task2 awake
4, task3 awake
6, task1 awake
End program

So whats wrong with the first results? Simply, more threads are needed, the callbacks happen sufficiently delayed to reuse the same thread. The Task Scheduler sees no need to allocate any more (or different) resources for you

your 2 functions have not the same delay

the first have a variable delay (1, 2 and 3 sec), and the second have constant delay (2 sec)

if you write

await Task.Delay(2000); //instead of await Task.Delay(1000 * delay);

you will have the same result than the second function

The threadid is not really an incremental value, when a thread is finished, its "id" becomes available

The same threadID is a different task in your case

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM