Anele Ngqandu

Anele Ngqandu

  • 1k
  • 428
  • 27.8k

Updating label with data from thread

Jun 11 2018 7:49 AM

I am trying to update a label in windows forms. The action is happening in a separate class but while the action is happening on a separate class. The label should be updated, but things seem to be not working. Kindly assist

Below is the Back code of the form ProcessingUI

  1. public partial class ProcessingUI : Form  
  2. {  
  3.     private void start_Click(object sender, EventArgs e)  
  4.     {  
  5.         StartProcessingTask();  
  6.     }  
  7.   
  8.      private void StartProcessingTask()  
  9.     {  
  10.         if (_isRunning)  
  11.             return;  
  12.   
  13.         _isRunning = true;  
  14.   
  15.         _taskToken = new CancellationTokenSource();  
  16.   
  17.             Task.Factory.StartNew(() =>  
  18.             {  
  19.                 while (_isRunning)  
  20.                 {  
  21.   
  22.                     var data = _processing.Processdata(lblCounter, _taskToken);  
  23.                     if (data.Success)  
  24.                         _isRunning = false;  
  25.                     if (_taskToken.IsCancellationRequested)  
  26.                         return;  
  27.                 }  
  28.   
  29.             });  
  30.   
  31.     }  
  32.   
  33.     public delegate void SetStatusCallback(string message);  
  34.     public void UpdateStatus(string message)  
  35.     {  
  36.         if (this.lblCounter.InvokeRequired)  
  37.         {  
  38.   
  39.             this.Invoke(new SetStatusCallback(UpdateStatus),   
  40.                  message);                                     
  41.         }  
  42.         else  
  43.             this.lblCounter.Text = message;  
  44.     }  
  45. }  
Then here is a separate class that has the action, basically its just updating. Now on update I just want to pass the record that is being updated. So i call the Method from the form and use it in this class.
  1. public class Processing  
  2.    {  
  3.         public Results Processdata(CancellationTokenSource taskToken)  
  4.        {  
  5.        foreach (var record in dataCases)  
  6.                {  
  7.           //Doing other things here like updating  
  8.             new ProcessingUI().UpdateStatus(record.RequestReference);//This is the method I am calling from the form.  
  9.            }  
  10.   
  11.        }  
  12.    }  
 

Answers (6)