Wednesday, December 13, 2017

Different between Multi Thread and Asynchronous

  • Synchronous: you cook the eggs, then you cook the toast.
  • Asynchronous, single threaded: you start the eggs cooking and set a timer. You start the toast cooking, and set a timer. While they are both cooking, you clean the kitchen. When the timers go off you take the eggs off the heat and the toast out of the toaster and serve them.
  • Asynchronous, multithreaded: you hire two more cooks, one to cook eggs and one to cook toast. Now you have the problem of coordinating the cooks so that they do not conflict with each other in the kitchen when sharing resources. And you have to pay them.
  • Threading is about workers; Asynchronous is about tasks
  • Tasks where some tasks depend on the results of others; as each task completes it invokes the code that schedules the next task that can run, given the results of the just-completed task. But you only need one worker to perform all the tasks, not one worker per task.

async and await

  • 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();
}