线程C#应用程序崩溃

时间:2011-02-18 23:57:54

标签: c# multithreading

大家好我有c#和线程问题,我对此很新,我做错了什么?

public System.Windows.Forms.TextBox text_box;

public static Thread object_t = new Thread ();
public static Thread worker_thread = new Thread (object_t.execute_t);


public Imagine_test ()
{
    InitializeComponent ();
this.Text = "title";
}
private void InitializeComponent ()
{
this.text_box = new System.Windows.Forms.TextBox ();
this.SuspendLayout ();
this.text_box.Name = "text_box";
this.text_box.Location = new System.Drawing.Point (5, 5);
this.text_box.Multiline = true;
this.text_box.Height = 50;
    this.text_box.Width = 500;
this.text_box.BorderStyle = 0;
this.ClientSize = new System.Drawing.Size (510, 60);
this.Controls.AddRange (new System.Windows.Forms.Control[] { this.text_box });
Load_func ();
this.ResumeLayout (false);
}

public static void Main ()
{
Application.Run (new Imagine_test ());          
}

public void Load_func ()
{
text_box.AppendText ("lorem");
worker_thread.Start ();

while (!worker_thread.IsAlive);
    Thread.Sleep (1);
    object_t.opreste_fir1 ();
    worker_thread.Join ();
    }
 }

 public class Thread : Imagine_test
 {
      public void execute_t ()
  {
    while (!_shouldStop) {
        //Thread.Sleep(5000);
        // run code
        text_box.AppendText ("some text");
     }
 }

 public void opreste_fir1 ()
 {
      _shouldStop = true;
 }

 private volatile bool _shouldStop;

1 个答案:

答案 0 :(得分:1)

您无法从与创建它的线程不同的线程访问Control的成员。

此行将导致异常:

 text_box.AppendText ("some text");

您需要将回调编组回用户界面线程:

 text_box.Invoke(new Action( () => text_box.AppendText("some text") ) );