Form UI Freeezes even after using Backgroundworker when using Flickr.Net API

拟墨画扇 提交于 2019-12-31 05:15:09

问题


Im trying to upload some images using the Flickr.net API.The Images are uploaded but the User Interface freezes.I have inserted the code for uploading in a Background worker

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    foreach (var item in imagelist)
    {
        flickr.UploadPicture(item, Path.GetFileName(item), null, null, true, false, true);
    }
    MessageBox.Show("Success");
}

The flickr object is created earlier from another form and passed to this form. I call the worker with if(worker.IsBusy==false){backgroundWorker1.RunWorkerAsync();} when a button is clicked.


回答1:


Two common causes for this, your snippet is way too brief to narrow down which it might be. First is the ReportProgress method, the event handler runs on the UI thread. If you call it too often then the UI thread can get flooded with invoke requests and spend too much time to handle them. It doesn't get around to doing its regular duties anymore, like responding to paint requests and processing user input. Because as soon as it is done handling a invoke request, there's another one waiting to get dispatched. The UI thread isn't actually frozen, it just looks like it is. The net effect is the same. You'll need to fix it by slowing down the worker or call ReportProgress less often.

The second cause is your flicker object not being thread-safe and itself ensuring that it is used in a thread-safe way. By marshaling the call from the worker thread to the UI thread automatically. This is very common for COM components, this kind of marshaling is a core feature of COM. Again the UI thread isn't actually frozen, but it still won't handle paint and input since it is busy uploading a photo. You'll need to fix it by creating the flicker object on the worker thread. With good odds that you can't do this with a BackgroundWorker, such a component often needs an STA thread that pumps a message loop. Which requires Thread.SetApartmentState() and Application.Run().




回答2:


If you are doing something like:

while(worker.IsBusy)
{
}

to wait for it to finish, this will hang because it ties up the UI thread in the loop and since the background worker needs to invoke onto the UI thread to set the busy property safely there is a dead lock.



来源:https://stackoverflow.com/questions/11272482/form-ui-freeezes-even-after-using-backgroundworker-when-using-flickr-net-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!