- async to create asynchronous method.
- await is wait until the process is complete
- If windows form has Async, it will show "loading" label and you can move form.
- Without Async, the form will hang and unhang when the task is finish.
Task
public async void btnProcess_click()
{
Task<int> task = new Task<int>(CountChacaracter); //Function
task.Start();
lblCount.text = "Loading. Please wait";
int count = await task; //wait for result
lblCount.text = count.ToString();
}
Thread
UI thread (main thread) is invoke a new thread, you need to thread join to join back the thread. But It will Block the UI cannot move to wait the result.
public async void btnProcess_click()
{
int count = 0;
Thread thread = new Thread(() => { count =
CountChacaracter(); });
thread.Start();
lblCount.text = "Loading. Please wait";
thread.Join();
lblCount.text = count.ToString();
}
With this, you can move the UI, but is not correct way, because only UI thread can modify the control, (it may or may not work, depend on luck)
Thread thread = new Thread(() =>
{
count = CountChacaracter();
lblcountText = count.tostring();
});
This is correct way, and same result as Task. But code is complicated, so use TASK!!
public async void btnProcess_click()
{
int count = 0;
Thread thread = new Thread(() =>
{
count = CountChacaracter();
Action action = new Action(SetLabel(count));
this.BeginInvoke(action);
});
thread.Start();
lblCount.text = "Loading. Please wait";
}
private void SetLabel(int count)
{
lblCount.text = count.ToString();
}