Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 463
Banshee Avatar asked Feb 22 '23 04:02

Banshee


1 Answers

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.

like image 107
Jon Skeet Avatar answered Mar 08 '23 11:03

Jon Skeet