Winform and threading (C#)

本文关键字:threading and Winform | 更新日期: 2023-09-27 18:30:10

我在使用线程更新UI的winform应用程序中遇到问题。我的应用程序可以从云端上传和下载文件。同时,我还在同一窗口上显示网速详细信息。这三个操作(上传、下载、显示n/w速度)由3个不同的线程调用。问题是,当我开始下载/上传时,整个窗口冻结,n/w速度显示不刷新(它被写为每隔1秒刷新一次)。会有什么问题?提前谢谢。

代码如下。。。和我为下载而写的一样。如果我先调用**上传**,然后一个接一个地调用**下载**,第一个线程将暂停,下载线程将启动。**下载**完成后,**上传**继续。这不是平行的。此外,UI不会立即响应其他按钮单击或窗口调整大小、移动操作。

public delegate void UploadDelgt();
UploadDelgt UpldDlgtObj;
 private void Form1_Load(object sender, EventArgs e)
{
    UpldDlgtObj = new UploadDelgt(DoUpload);
}
public void load()
{
    Form1 form = this;
    form.Invoke(UpldDlgtObj);
}
private void button1_Click(object sender, EventArgs e)
{
    thrd = new Thread(new ThreadStart(load));
    thrd.Start();
    thrd.IsBackground = true;
}
public void DoUpload()
{
//uploads file block by block and updates the progressbar accordingly..
}

Winform and threading (C#)

这三个操作(上传、下载、显示n/w速度)由3个不同的线程调用。问题是,当我开始下载/上传时,整个窗口都冻结了

您的一个工作线程正在阻塞UI线程。请确保这些操作都没有在UI线程上完成,并且按照此处所述使用InvokeRequired/Invoke:http://www.codeproject.com/Articles/37642/Avoiding-InvokeRequired

您的UI冻结是因为您正在load方法中调用form.Invoke。来自MSDN关于Invoke:Executes the specified delegate on the thread that owns the control's underlying window handle.因此,如果您在单独的线程中调用DoUpload,它仍然在GUI线程(拥有表单句柄)上执行,因为它是用Invoke调用的。