Banshee
Banshee

Reputation: 15807

Blocking with Task?

I try to use tasks in my application like this :

Task test;
test = Task.Factory.StartNew(() => general.Login(loginName, password));
MyTextBox.Text = "test text";

It will be the UI thread that makes this call and I need it to be blocked until the worker thread returns from the service but I do not want the UI to freeze.

I could use a ContinueWith but this will split my login method and this makes it harder to follow. I do also need the main UI thread to run the rest of the code in this method.

How do I solve this?

Upvotes: 4

Views: 3072

Answers (2)

Tudor
Tudor

Reputation: 62439

There is no way to wait for a thread without blocking the waiting thread. What you can do is something like:

fire task
do some other task
wait for task  // hopefully the task finished by now

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500065

This is precisely the problem that async in C# 5 solves. For the moment, you basically have to split your code. It's a pain, but that's the way it is. (Your description is slightly off, by the way - you don't want to block the UI thread... you want to "not perform the second part of your logic" until the worker thread returns. Not quite the same thing :) (You may also want to disable some other bits of the UI, but we can't tell for sure.)

It's worth getting a head start on the async feature - see the Visual Studio async home page for a lot of resources.

Upvotes: 8

Related Questions