简体   繁体   中英

Run Methods inside a thread synchronously C# .net core

I am starting a background thread in my .net core controller like this

var t = new System.Threading.Thread(() => LongRunningTask()) 
                                         { IsBackground = true };
t.Start();

Then My long running method is something similar to this

public void LongRunningTask(){
    
    A();
    B();
    C();
 }

However sometimes I noticed method C executed before the end of method A. Are there any way to make these AB C methods executed each after the other.

Or else are there ant better approach to run this long-running tasks without user to wait until all these finishes?

They are started one after another on the same thread so A will always finish before B starts assuming A is synchronous and doesn't for example include any await statements that will cause it to return before you consider it to be finished.

If the methods are asynchronous, they should return a Task and you should await them, eg:

var t = new System.Threading.Thread(async () => await LongRunningTask())
{ IsBackground = true };
t.Start();

async Task LongRunningTask()
{
    await A();
    await B();
    await C();
}

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