In the BackgroundWorker
thread (started with RunWorkerAsync()
) I want to download files from a server via HttpWebRequest
. As soon as I call GetResponse()
the GUI is remains freezed while the file is downloaded from the server. This actually shouldn't happen as a BackgroundWorker is more or less the same as a thread with some decoration like progress handling and cancellation. Can anybody explain me why this is happening?
Here the code snippet :
if ((lRequest = (HttpWebRequest)WebRequest.Create(lURL)) != null)
{
if ((lResponse = lRequest.GetResponse()) != null)
{
lRemoteStream = lResponse.GetResponseStream();
lLocalStream = File.Create(lTempFileName);
do
{
lBytesRead = lRemoteStream.Read(lTemp, 0, 开发者_开发问答lTemp.Length);
lLocalStream.Write(lTemp, 0, lBytesRead);
} while (lBytesRead > 0);
}
}
Need to see more code to offer help.
One way I had a similar issue happen to me was when I was sending a lot of progress to the UI very quickly which in essence froze it. So while my main task was running on another thread like yours, my updates to the UI were extremely fast that it affected the UI thread negatively. Maybe you're doing something similar here?
in the meantime i've found the problem and if i had listened to you you had probably answered my question already :/
if you start BackgroundWorker threads be careful you don't point back to the UI main thread. in my case i did it this way :
private void BW_FriendInRequest_DoWork(object sender, DoWorkEventArgs e)
{
while (true)
{
if (this.isLoggedIn)
listIncomingRequests();
Thread.Sleep(Config.mMessagesCheckSleep);
}
}
private delegate void listIncomingRequestsDelegate();
private void listIncomingRequests()
{
if (InvokeRequired)
{
listIncomingRequestsDelegate d = new listIncomingRequestsDelegate(listIncomingRequests);
this.Invoke(d, new object[] { });
return;
}
...
}
as soon as i removed the "InvokeRequired" the freezing effect had gone.
精彩评论