What is the difference between task and thread?

后端 未结 8 1751
庸人自扰
庸人自扰 2020-11-22 02:45

In C# 4.0, we have Task in the System.Threading.Tasks namespace. What is the true difference between Thread and Task. I did s

8条回答
  •  天涯浪人
    2020-11-22 03:21

    I usually use Task to interact with Winforms and simple background worker to make it not freezing the UI. here an example when I prefer using Task

    private async void buttonDownload_Click(object sender, EventArgs e)
    {
        buttonDownload.Enabled = false;
        await Task.Run(() => {
            using (var client = new WebClient())
            {
                client.DownloadFile("http://example.com/file.mpeg", "file.mpeg");
            }
        })
        buttonDownload.Enabled = true;
    }
    

    VS

    private void buttonDownload_Click(object sender, EventArgs e)
    {
        buttonDownload.Enabled = false;
        Thread t = new Thread(() =>
        {
            using (var client = new WebClient())
            {
                client.DownloadFile("http://example.com/file.mpeg", "file.mpeg");
            }
            this.Invoke((MethodInvoker)delegate()
            {
                buttonDownload.Enabled = true;
            });
        });
        t.IsBackground = true;
        t.Start();
    }
    

    the difference is you don't need to use MethodInvoker and shorter code.

提交回复
热议问题