在异步背景工作者上形成冻结

时间:2015-11-20 19:42:00

标签: c# backgroundworker

一直在寻找答案,但我无法弄明白。我不像其他语言那样熟悉C#,任何信息都会有所帮助。无论我尝试什么,在运行backgroundworker时,表单都会冻结。

backgroundWorker1.RunWorkerAsync(filepath);

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        string filepath = e.Argument.ToString();

        using (Image image = Image.FromFile(filepath))
        {
            using (MemoryStream ms = new MemoryStream())
            {
                image.Save(ms, ImageFormat.Png);
                byte[] imageBytes = ms.ToArray();
                string base64String = Convert.ToBase64String(imageBytes);
                e.Result = base64String;
            }
        }  
        System.Threading.Thread.Sleep(1000);
    }

private void backgroundWorker1_RunWorkerCompleted(object sender,   RunWorkerCompletedEventArgs e)
    {
        textBox1.Text = e.Result.ToString();
    }

2 个答案:

答案 0 :(得分:0)

您的代码看起来正确。但是,您暂停后台线程1秒钟。要避免这种行为,您应该删除这行代码:

 System.Threading.Thread.Sleep(1000);

答案 1 :(得分:0)

您应该考虑使用async / await,因为Microsoft建议使用它来代替BackgroundWorker。

假设您的工作人员在按钮点击事件中被触发,它将如下所示:

 private async void button1_Click(object sender, EventArgs e)
    {
        textBox1.Text = await Task.Run(() =>
        {
            using (Image image = Image.FromFile(filepath))
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    image.Save(ms, ImageFormat.Png);
                    byte[] imageBytes = ms.ToArray();
                    string base64String = Convert.ToBase64String(imageBytes);
                    return base64String;
                }
            }
        });
    }