Asynchronous Method call

Posted by Hmanjarawala under C# category on | Points: 40 | Views : 1636
    // Class that contains event and event handler
public class Task
public delegate void UpdateStatusEventHandler(string text, int total, int current);
public delegate void UpdateTextEventHandler(string text);
public delegate void UpdateProgressBarEventHandler(int total, int value);

public event UpdateStatusEventHandler UpdateStatus;
public event UpdateTextEventHandler UpdateText;
public event UpdateProgressBarEventHandler UpdateProgressBar;

handle this class events on Window Application forms. For that you haveto register this events:

            //Write this code on form load or form's constructor
Task task = new Task();
task.UpdateProgressBar += new Task.UpdateProgressBarEventHandler(task_UpdateProgressBar);
task.UpdateStatus += new Task.UpdateStatusEventHandler(task_UpdateStatus);
task.UpdateText += new Task.UpdateTextEventHandler(task_UpdateText);

now define delegates on form that handle this events asynchronously.

private delegate void delUpdateStatus(Label lbl, string text, int total, int current);        
private void mUpdateStatus(Label lbl, string text, int total, int current)
if (lbl.InvokeRequired)
lbl.BeginInvoke(new delUpdateStatus(mUpdateStatus1), lbl, text, total, current);

private void mUpdateStatus1(Label lbl, string text, int total, int current)
lbl.Text = string.Format("{0}/{1}\n {2}", current, total, text);

this way you can update label text asynchronously.

and at last write down method that calls when Task classevents fired

      private void task_UpdateStatus(string text, int total, int current)
eUpdateStatus(lblStatus, text, total, current);

Comments or Responses

Login to post response