Tuesday, August 29, 2017

Windows Forms Multi Threaded Background Job Application

When you are working on distributed architecture application using Multi Threads developer usually come across Cross Thread error.
Error Description : Cross-thread operation not valid: Control 'progressBar1' accessed from a thread other than the thread it was created on.

Whenever we try to access control object which are part of main thread and if you try to change that control object property value you will receive Cross Thread operation error.
It error description suggest that you are trying to do Cross-Thread operation which is not valid.

To produce this error in my example i am going to use small Windows Forms App ( Parent Child ).

  1. Parent Form which is Main Form and it has menu items to open Child Form
  2. Child Form which will start the small loop in thread using "Start Loop" button
  3. From the loop we try to set value of Progress bar and Status label text.
  4. Once you click "Start Loop" button you can see Cross Thread error because Progress bar control is a part of Main Thread and we are trying to access directly to sub thread.

WFBackgroundJob1.cs

This error you can resolve using Thread.Invoke but i am resolving this error using Background Job in my example. Let's take a look simple example which start Background Job under worked thread and it's progress using backgroundWorker1_ProgressChanged event.
Your job runs in background asynchronously and user able to continue working on system as system won't hang even we are running loop.

  1. Parent Form which is same like previous Main Form and it has menu items to open Child Form
  2. Child Form which start the small loop in backgroundWorker1_DoWork event using button "Start Loop" which start loop asynchronously backgroundWorker1.RunWorkerAsync();
  3. DoWork report the progress using backgroundWorker1.ReportProgress method
  4. In example 2 arguments added in ReportProgress method one is percentProgress and second is Progress Status as Text.
  5. Background job control WorkerReportProgress property need to set True before using ReportProgress method

Please get the sample CSharp code as mentioned

WFBackgroundJob2.cs

Please post your questions or comments bellow. Thank you !

No comments:

Post a Comment