日期:2014-05-18 浏览次数:20851 次
public class Test { int _index = 0; Thread _thread; public int Index { get { return _index; } set { _index = value; } } public Thread Thread { get { return _thread; } set { _thread = value; } } public void Run() { string result = DateTime.Now.ToString("HH:mm:ss:fff") + " " + _thread.ManagedThreadId.ToString("00") + " is " + _thread.IsAlive.ToString() + ":" + _index.ToString(); try { File.AppendAllText("result.txt", result + "\r\n"); } catch (Exception ex) { File.AppendAllText("result_failed.txt", result + " " + ex.Message + "\r\n"); } //请问在这里如何给textBox1.Text赋值 result 呢:( //想实现每一个进程执行完后都在textBox1.Text中输出 result 结果 } }
using System; using System.IO; using System.Threading; using System.Windows.Forms; namespace 多线程操作FORM { public delegate void ChangeTextBox(string text); public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { for (int i = 0; i < 24; i++) { Test test = new Test(); test.Index = i; test.WorkCompleted += new EventHandler(test_WorkCompleted); Thread thread = new Thread(new ThreadStart(test.Run)); thread.IsBackground = true; test.Thread = thread; thread.Start(); //Thread.Sleep(1); } //textBox1.Text = "完成"; } void test_WorkCompleted(object sender, EventArgs e) { int i = ((Test)sender).Index; if (this.InvokeRequired) { this.Invoke(new ChangeTextBox(ChangeTextBoxMethod), i.ToString()); } else { ChangeTextBoxMethod(i.ToString()); } } private void ChangeTextBoxMethod(string value) { textBox1.Text += string.Format("Work {0} done.{1}", value, Environment.NewLine); } } public class Test { int _index = 0; Thread _thread; public event EventHandler WorkCompleted; public int Index { get { return _index; } set { _index = value; } } public Thread Thread { get { return _thread; } set { _thread = value; } } public void Run() { string result = DateTime.Now.ToString("HH:mm:ss:fff") + " " + _thread.ManagedThreadId.ToString("00") + " is " + _thread.IsAlive.ToString() + ":" + _index.ToString(); try { File.AppendAllText("result.txt", result + "\r\n"); } catch (Exception ex) { File.AppendAllText(string.Format("result{0}_failed.txt", Index.ToString()), result + " " + ex.Message + "\r\n"); } if (WorkCompleted != null) { WorkCompleted(this, EventArgs.Empty); } //请问在这里如何给textBox1.Text赋值 result 呢:( //想实现每一个进程执行完后都在textBox1.Text中输出 result 结果 } } }