user3373870
user3373870

Reputation: 1466

Async Task in Windows form doesn't return result

Can someone explain to me why this code doesn't work (the result is not assigned to the textbox's text property)

private async Task<string> NumToString(int num)
{

  return await new Task<string>(()=>{
     return  num.ToString();

     });
}

here is the call:

 private async void button2_Click(object sender, EventArgs e)
        {
           // TaskScheduler context = TaskScheduler.FromCurrentSynchronizationContext();
            var content = await NumToString(1);
          textBox1.Text = content;

        }

Also, If I un-comment the TaskScheduler line the click event gets fired but the NumTostring(1) doesn't fire.

Upvotes: 0

Views: 622

Answers (1)

max
max

Reputation: 34407

You should start the task, not just create it:

private Task<string> NumToString(int num)
{
    return Task.Run(() => num.ToString());
}

Upvotes: 6

Related Questions