Does the phonverter and the TPL task have the same ManagedThreadID?

I have a Backgroundworker whose purpose is to complete tasks sequentially in the background. Now one task is performed in a multithreaded way. This means that Backgroundworker will create multiple threads. I use a parallel task library, so I use Task.Factory.StartNew to create multiple tasks.

After completing the tasks, the Phonoverter waits for their completion.

Now I print ManagedThreadID Backgroundworker and all managed tasks ManagedThreadID. I found that BackgroundWorker ManagedThreadID always matches the first ManagedThreadID task. I think this should not happen, so I can’t explain. I think the Backgroundworker thread should be different from all the tasks it creates, so ManagedThreadID should be different from each other.

Can someone explain why this scenario is happening? Thank you very much.

Edit:

The code is similar to this:

Backgroundworker.Run(){
    // Print Thread.CurrentThread.ManagedThreadID.
    var task = Task.Factory.StartNew(action1); // action1, action2 also print ManagedThredID.
    taskList.Add(task);
    task = Task.Factory.StartNew(action2);
    taskList.Add(task);
    ... // Several other tasks.

    foreach(var task in taskList) task.Wait();
}

You will find that one task has the same ManagedThreadID as Backgroundworker.

+3
source share
4 answers

, TPL , BackgroundWorker. , , , .

, , , Task.Wait. Task.Wait "Inlining" Team of Parallel Programming Team.

Waitd on , Wait . , , Wait .

+5

Background , TPL. , , , TPL . , TPL, TPL , , , , - .

, , , .

+2

, , , , (): TPL , .

When you create a task, it is not immediately / permanently connected with the flow. A task is a task that is placed in a queue, and queues (queues) are served by worker threads. Thus, it may be that the Bgw task is suspended and its thread returns to the pool, or more directly, this can be done using the Wait () function:

// thread A
var t1 = Task.Startnew(...);
var t2 = Task.Startnew(...);
t1.Wait();  // Thread A is idle/available so Wait can execute t1
t2.Wait();  
+2
source

Use TaskCreationOptions.LongRunning to avoid re-cycling the desktop.

+1
source

Source: https://habr.com/ru/post/1765283/


All Articles