问题
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