简体   繁体   中英

Winform and threading (C#)

I have a problem with winform application which uses threads to update the UI. My application does upload and downloading of files from cloud. Same time I am also displaying Network speed details on the same window. These three operations (upload, download, display n/w speed) are invoked by 3 different threads. Problem is, when I start download/upload, whole window freezes and n/w speed display doesn't refresh (it is written to refresh at every 1sec interval). what would be the problem? Thanks in advance.

Code is as follows... same way i have written for download. If I call **Upload** first and then **Download** one after the other, first thread will pause and download thread starts. once **Download** is done then **Upload** continues. Its not going in parallel. Also UI doesn't respond immediately for other button click or window resize, move actions.

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..
}

These three operations (upload, download, display n/w speed) are invoked by 3 different threads. Problem is, when I start download/upload, whole window freezes

One of your worker threads are blocking the UI thread. Make sure that none of those operations are done on the UI thread and that you use the InvokeRequired / Invoke as described here: http://www.codeproject.com/Articles/37642/Avoiding-InvokeRequired

Your UI freezes because you are calling form.Invoke in your load method. From MSDN about Invoke : Executes the specified delegate on the thread that owns the control's underlying window handle. So, thought you are calling DoUpload in a separate thread, it is still executed on the GUI thread (which owns the form handle), because it is called with Invoke .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM