Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threading: Application Freezes after using Thread.Join()

I understand that the .Join() causes the threads to pause and wait till a thread finishes its work but how can I avoid the UI from getting frozen? This is what my codes look like"

Thread dataThread = new Thread(()=> data = getData(id));
dataThread.Start();
dataThread.Join();

Thread storingThread = new Thread(()=> storeData(data));
storingThread.Start();

I need to have the Join since the first thread returns an object containing data that needs to be stored through the second thread. But this causes a UI freeze. How can I implement these in maybe a Background thread? What do yall think I should change?

like image 873
Dinuka Jay Avatar asked Oct 20 '25 20:10

Dinuka Jay


2 Answers

If you are using .Net framework >= 4.5 you can use Tasks

await Task.Run(() => data = getData(id));
await Task.Run(() => storeData(data));

Or in one command

await Task.Run(() => storeData(getData(id)));

If you don't have to wait till it's finished you can also do:

Task.Run(() => storeData(getData(id)));
like image 156
Simon Avatar answered Oct 23 '25 09:10

Simon


It seems you don't need two threads:

Thread dataThread = new Thread(() => storeData(getData(id)));
dataThread.Start();

Note, that Task is preferable to Thread. Also, you probably should make use of await.

like image 33
usr Avatar answered Oct 23 '25 10:10

usr