Jay
Jay

Reputation: 5084

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?

Upvotes: 4

Views: 4549

Answers (5)

Florian Moser
Florian Moser

Reputation: 2663

Use the async / await keywords. Small example code:

private async void Method()
{
     var result = await ExecuteAsync();
     // result == true 
}

private async Task<bool> ExecuteAsync()
{
     //run long running action
     return true;
}

In .net 4.0 you need to install Microsoft.Bcl.Async to use this feature.

A good introduction in this feature can be read on http://blog.stephencleary.com/2012/02/async-and-await.html

Upvotes: 2

ΩmegaMan
ΩmegaMan

Reputation: 31696

Put the whole work into one thread so the UI doesn't stop:

 ThreadPool.QueueUserWorkItem( () => storeData(getData(id)));

Or for .Net 4

Task.Factory.StartNew(() => storeData(getData(id)));

Upvotes: 2

Measurity
Measurity

Reputation: 1346

The answer has already been given. Just as an extra, I give mine.

You can also use ContinueWith like this:

Task<string>.Factory.StartNew(() => "Hey!").ContinueWith(t => Console.WriteLine(t.Result));

Upvotes: 2

Simon
Simon

Reputation: 1312

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)));

Upvotes: 4

usr
usr

Reputation: 171206

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.

Upvotes: 2

Related Questions