Pass task status information to a method on another thread

If you start a Task which is going to process a large job on another thread in order to keep your UI responsive you want to know the status information of that Task and maybe next to that you want to know the progress.

 If you try just to pass some information over the threads you will receive the dreadly thread error telling you that you cannot access you UI controls because it's on another thread.

A solution for that is to create an delegate and instantiate it with the method wich will update your UI.


       // the method wich will update the UI
        private void UpdateLabelWithStatus(int counter)
            lblstatus.Text = "We are at number" + counter.ToString();

Now create a instantiate the delegate to use this method from another thread:

        public delegate void UpdateStatusInformationDelegate(int counter);
        public UpdateStatusInformationDelegate UpdateStatusInformation;
        // int the constructor of you class instantiate
        UpdateStatusInformation = new UpdateStatusInformationDelegate(UpdateLableWithStatus);

Now you can pass information to the method by using invoke and this delegate:

        target.Invoke(UpateStatusInformation, mycounter);




Saving your comment....

Naam is verplicht!
Email is verplicht!
Opmerking is verplicht!