WiXXeY
WiXXeY

Reputation: 1001

Updating a Label with the backgroundworker progress

I am reading line by line console of an external exe with the help of a backgroundworker, i am assigning each line of console to a label. the problem is the label is not updating with the console line. code is given below

private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
    int i = 0;
    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.CreateNoWindow = true;
    startInfo.UseShellExecute = false;
    startInfo.FileName = EXELOCATION;
    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
    startInfo.Arguments = Program.path;
    startInfo.RedirectStandardOutput = true;
    try
    {
        // Start the process with the info we specified.
        // Call WaitForExit and then the using statement will close.
        using (exeProcess = Process.Start(startInfo))
        {
            using (StreamReader reader = exeProcess.StandardOutput)
            {
                string result;
                while ((result = reader.ReadLine()) != null)
                {
                    // object param = result;

                    e.Result = result;
                    bgWorker.ReportProgress(i++);
                }
            }
        }
    }
    catch
    {
        // Log error.
    }
}

private void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    label.Text = e.ToString();
    label.Refresh();
}

how can i solve this issue

Upvotes: 0

Views: 4449

Answers (3)

Hamidreza
Hamidreza

Reputation: 3128

try this:

label2.Invoke(new Action(() => { label2.Text = e.ToString(); }));
label2.Invoke(new Action(() => { label2.Refresh(); }));

Upvotes: 2

SWeko
SWeko

Reputation: 30892

If this is in another thread (and you are in a winforms application), you might need to use the Control.InvokeRequired

public void UpdateProgress (int progress)
{
  if (label.InvokeRequired)
  { 
     this.Invoke(()=> UpdateProgress(progress));
  }
  else
  {
     label.Text = progress.ToString();
  }
}

This method checks whether it's run on the UI thread, and if it is not, it calls itself on the UI thread. If it is already on the UI thread, it simply updates the label.

Upvotes: 0

dcastro
dcastro

Reputation: 68660

That code probably doesn't work because you're trying to update an UI element from a non-UI thread (aka background thread).

If you're using WPF, you should use the Dispatcher to request that the label be changed in the UI thread. If you're using another framework, try that framework's equivalent class.

In your ProgressChanged method, try this instead:

Application.Current.Dispatcher.BeginInvoke(
  DispatcherPriority.Background,
  () => {
    label.Text = e.ToString();
  });

Upvotes: 0

Related Questions