Tom Carroll Tom Carroll - 3 months ago 14
C# Question

Changing TextBox Value when task completed

I have a WinForms application that has two forms. On the first form the user enters some information and clicks the next button, this hides form1, loads form2 and fires a task (the function of which is on form1) that loads data from the database.

What I would like to do is on the second form have a text box that displays "Loading Data" whilst the task is running and then the count of the rows returned when the task has complete. All the while allowing the user to continue to enter data on form2.

This is the first time I have tried using tasks and

and I'm struggling to figure out a way to do this.

Task emailTask = new Task(() => FindCustomersForEmail(reg.Index));

MessageControl formMessageControl = new MessageControl();

Whats in my head is something like:

while (emailTask not complete)
txtEmailCount.Text = "Loading";
txtEmailCount.Text = customersToEmail.Rows.Count.ToString();


Why not just await on the Task?

// Note this is void because I'm assuming it's an event handler. 
// If it isn't this should be `async Task` instead.
public async void FindCustomersAsync()
    txtEmailCount.Text = "Loading";
    await Task.Run(() => FindCustomersForEmail(reg.Index));

    txtEmailCount.Text = customersToEmail.Rows.Count.ToString();

Side note - prefer using Task.Run instead of manually starting the Task.