How to display progress bar if using waithandle

Somewhere in the code, waitHandle is used to perform some action. However, the thing with waithandle is that the form freezes, waiting for the completion of some action. Thus, the following code will not work:

frmProgressBar.show(); int successOrFail = PerformSynchronousActionUsingWaitHandle(); frmProgressBar.close(); frmMainScreen.show(); 

This will not work, since frmProgressBar will be frozen instead. I really need to save line # 1, line # 3 and line # 4, but how can I rewrite the PerformSynchronousActionUsingWaitHandle () function so that the operation is still synchronous, but the progress bar is displayed. I can get around this by showing a progress bar in another thread, but the system design is such that it will be very dirty.

+1
source share
4 answers

you want to run PerformSynchronousActionUsingWaitHandle in the thread so that it does not block the ui thread.

  public event EventHandler<WorkCompleteArgs> WorkComplete; private void StartClick(object sender, EventArgs e) { //hook a complete event this.WorkComplete += new EventHandler(OnWorkComplete); //do start code //run the PerformSynchronousActionUsingWaitHandle process in a thread Thread thread = new Thread(new ThreadStart(PerformSynchronousActionUsingWaitHandle)); thread.Start(); } private void OnWorkComplete(object sender, EventArgs e) { //cross thread if (this.InvokeRequired) { this.BeginInvoke(new EventHandler(OnWorkComplete), new object[] { sender, e }); return; } //un hook this.WorkComplete -= new EventHandler(OnWorkComplete); //do complete code } private void PerformSynchronousActionUsingWaitHandle() { Thread.Sleep(1000); if (WorkComplete != null) { //use event args to return the functions result if needed. WorkComplete(this, new WorkCompleteArgs(true)); } } public class WorkCompleteArgs { public WorkState {get;private set;} public WorkCompleteArgs(bool workState) { this.WorkState = workState; } } 
+1
source

Use two different threads to handle this ... one thread for the progress bar and one thread for PerformSynchronousActionUsingWaitHandle () .. Hope this helps in some way

0
source

Have you tried using BackgroundWorker instead? However, you need to rewrite the method that performs the synchronous task.

0
source

All Articles