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
- public partial class ProcessingUI : Form
- {
- private void start_Click(object sender, EventArgs e)
- {
- StartProcessingTask();
- }
- private void StartProcessingTask()
- {
- if (_isRunning)
- return;
- _isRunning = true;
- _taskToken = new CancellationTokenSource();
- Task.Factory.StartNew(() =>
- {
- while (_isRunning)
- {
- var data = _processing.Processdata(lblCounter, _taskToken);
- if (data.Success)
- _isRunning = false;
- if (_taskToken.IsCancellationRequested)
- return;
- }
- });
- }
- public delegate void SetStatusCallback(string message);
- public void UpdateStatus(string message)
- {
- if (this.lblCounter.InvokeRequired)
- {
- this.Invoke(new SetStatusCallback(UpdateStatus),
- message);
- }
- else
- this.lblCounter.Text = message;
- }
- }
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.
- public class Processing
- {
- public Results Processdata(CancellationTokenSource taskToken)
- {
- foreach (var record in dataCases)
- {
- //Doing other things here like updating
- new ProcessingUI().UpdateStatus(record.RequestReference);//This is the method I am calling from the form.
- }
- }
- }
Hemant JindalPosted Jun 12, 2018, 4:01 AM
Anele NgqanduPosted Jun 12, 2018, 3:51 AM
Hemant JindalPosted Jun 12, 2018, 3:36 AM
You can also use BackgroundWorker. I have created a sample application for your reference. Hope this help you
public class ProcessManager
{
readonly BackgroundWorker worker = new BackgroundWorker();
public void StartProcess()
{
worker.DoWork += Worker_DoWork;
worker.ProgressChanged += Worker_ProgressChanged;
worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
worker.RunWorkerAsync();
}
private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//update your label here
}
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 1000; i++)
{
//Add your code to process
Console.WriteLine("In progress");
Thread.Sleep(1000);
int percentage = (i + 1) * 100 / 1000;
worker.ReportProgress(1, null);
}
}
}
static void Main(string[] args)
{
ProcessManager processSomeThing = new ProcessManager();
processSomeThing.StartProcess();
Console.ReadLine();
}
Thanks
Hemant Jindal
Prakash ChasiyaPosted Jun 12, 2018, 12:16 AM
Anele NgqanduPosted Jun 12, 2018, 12:09 AM
Prakash ChasiyaPosted Jun 11, 2018, 11:41 PM