Question

I need to use controls on another thread. I know that i need to invoke them but dont know how. This is my code:

Thread threadWriteLog = new Thread(new ThreadStart(this.WriteLog));
threadWriteLog.Start();

private void WriteLog()
    {
        date = DateTime.Now;
        using (StreamWriter swLog = new StreamWriter(String.Format("{0}\\RoutesLogs\\{1}.log", Settings.Instance.Paths.SDCard, textName), true))         //zapisovanie logu
        {
            if (btnStartPause.Text == "Start Recording")
                swLog.WriteLine(String.Format("Route start: {0}", date.ToString(format)));
            else if (btnStartPause.Text == "Pause Recording")
                swLog.WriteLine(String.Format("Route pause: {0}", date.ToString(format)));
            else if (btnStartPause.Text == "Resume Recording")
                swLog.WriteLine(String.Format("Route resume: {0}", date.ToString(format)));
        }
    }

Can u write me a solve code?

No correct solution

OTHER TIPS

Rather than having the other thread marshal back to the UI thread just to read data from a control, pull the string text out of the control before string the thread and then provide that string to the new thread when creating it. The easiest way of doing this is through a lambda that closes over the information:

string text = control.Text;
Thread thread = new Thread(() => WriteLog(text));
thread.Start();

Then just add a string parameter to WriteLog for the data. You can do this for each piece of information needed.

Beyond simply preventing cross thread exception errors, a key aspect of this design is that you have now separated your business logic from your user interface, which makes the application much easier to maintain going forward.

Simple answer: I think the .Text Methods should work without invocation.

Have you already tried it out?

[Edit]

Here is an short example how to do the invocation:

public class Dlg
{
   public delegate void UpdateConnLabel(string txt);
   private event UpdateConnLabel _UpdateConnLabel;

   public Dlg()
   {
      InitializeComponent();
      _UpdateConnLabel = new UpdateConnLabel(DoUpdateConnectionLabel);
   }

   public void UpdateConnectionLabel(String txt)
   {
      this.Invoke(_UpdateConnLabel, new object[] { txt });
   }

   private void DoUpdateConnectionLabel(string txt)
   {
      label_connection.Text = txt;
   }

}

You simply call UpdateConnectionLabel("hello World"); everywhere you want to update the text on the label.

I hope this helps to understand the mechanism.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top