Sleiman Jneidi
Sleiman Jneidi

Reputation: 23349

Improving Task code to achieve async await

I am creating a task and then assign a thread that waits for the task to be completed and then modify the UI.

 string txt = txtHelloMessage.Text;
 HelloTask = Task<string>.Factory.StartNew(
            () =>
            {
                string msg = client.SayHello(txt);
                return msg;
            }
            );
 new Thread(
           () =>
            {
                while (true)// waiting for completion, I think that this is wrong
                {
                    if (HelloTask.IsCompleted)
                    {
                        this.Dispatcher.Invoke((Action)delegate() { txtHelloMessage.Text = HelloTask.Result; });
                        break;

                    }
                }

            }
            ).Start();

Is this good practice?

Upvotes: 1

Views: 1103

Answers (2)

Daniel Mann
Daniel Mann

Reputation: 59055

Since you're using .NET 4.5 / C# 5, you could use the await keyword. Here's a really stupid, simple example:

    private async void button1_Click(object sender, EventArgs e)
    {
        await GetSomeTextForSomeReason();
    }

    private async Task GetSomeTextForSomeReason()
    {
        var s = await Task.Factory.StartNew(() =>
                                  {
                                      for (int i = 0; i < 500000000; i++) ; // simulate a delay
                                      return "This is text";
                                  });
        textBox1.Text = s;
    }

Upvotes: 2

Henk Holterman
Henk Holterman

Reputation: 273701

No, it's not good practice.

You're using a very heavy and expensive Thread to handle the outcome of a lightweight (cheap) Task.

In this case you could just let the Task itself do the Invoke(), or use a continuation.

But the code looks very artificial, maybe post something closer to your real problem.

Upvotes: 1

Related Questions