How to update the progress bar through Backgroundworker in C#? [duplicate]

可紊 提交于 2019-12-13 09:59:12

问题


I have a Backgrounder worker which generates the Excel file through the C# function GenerateExcel(). Within the GenerateExcel() function, I am using the progressbar to update the status. However, it is throwing an exception, that I cannot modify the GUI control. Any idea what could be the error in the code ?

BackgroundWorker backgroundWorker1 = new BackgroundWorker();

backgroundWorker1.DoWork += new DoWorkEventHandler(delegate(object o, DoWorkEventArgs args)
{
    GenerateExcel(FileName, 1);
});

backgroundWorker1.RunWorkerAsync();

Thanks


回答1:


You need to create an instance of the BackgroundWorker.ReportProgress event. Then update the progress bar in that method.

BackgroundWorker.ReportProgress += new ReportProgressEventHandler()....

(Syntax is probably incorrect, but you get the idea)




回答2:


Hope you are getting - System.InvalidOperationException – Cross-thread operation not valid - Exception - This post might help you - http://www.dotnetthoughts.net/system_invalidoperationexception_cross_thread_operation_not_valid/




回答3:


You need to control the Backgroundworker event ProgressChanged and, inside the main method, instead of changing the progressbar, use this:

BW1.ReportProgress(iProg)

And in your event, modify the Progressbar retriving the value in the ProgressChangedEventArgs:

ProgressBar1.Value = e.ProgressPercentage


来源:https://stackoverflow.com/questions/18465318/how-to-update-the-progress-bar-through-backgroundworker-in-c

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