控制另一个线程

时间:2014-02-24 13:06:40

标签: c# multithreading controls compact-framework invoke

我需要在另一个线程上使用控件。我知道我需要调用它们但不知道如何。这是我的代码:

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)));
        }
    }

你可以给我写一个求解代码吗?

2 个答案:

答案 0 :(得分:1)

而不是将其他线程封送回UI线程只是为了从控件中读取数据,而不是将字符串文本从控件中拉出来,然后将字符串,然后将该字符串提供给新的创建它时的线程。最简单的方法是通过一个关闭信息的lambda:

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

然后只需为WriteLog添加一个字符串参数即可获得数据。您可以为所需的每条信息执行此操作。

除了简单地防止跨线程异常错误之外,此设计的一个关键方面是您现在已将业务逻辑与用户界面分开,这使得应用程序更容易维护。

答案 1 :(得分:0)

简单回答:我认为.Text方法应该在没有调用的情况下工作。

你已经试过了吗?

[编辑]

以下是如何进行调用的简短示例:

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;
   }

}

您只需在要更新标签上文字的任何地方拨打UpdateConnectionLabel("hello World");

我希望这有助于理解这种机制。