2011-02-18 55 views
0

嗨,大家好我有问题与C#和线程,我对此相当新,我做错了什么?主题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; 
+0

您好,欢迎堆栈溢出。始终努力提供尽可能完整的问题。在这种情况下,你应该发布*为什么*你认为有问题,并且*症状*。 – 2011-02-19 00:03:55

+0

你的调试器发生了什么?它看起来像你试图从一个拥有它的线程以外的线程利用控制。任何控件修改都应该从对象中暴露出来,并调用以在UI线程上运行。 – Avilo 2011-02-19 00:04:28

回答

1

您不能从不同于创建它的线程访问Control的成员。

这条线将导致异常:

text_box.AppendText ("some text"); 

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

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