form是一个类,线程函数在另一个类中,如何更新界面上的内容呢?
举个最简单的例子:
form:using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;namespace test
{
delegate void AppendInfo(string str);
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
WorkThread wt = new WorkThread();
ThreadStart ts = new ThreadStart(wt.execute); Thread thread = new Thread(ts);
thread.Start();
} public void AppInfo(string str)
{
this.textBox1.Text = this.textBox1.Text + str + "\n";
}
}
}
线程类:using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;namespace test
{
class WorkThread
{
public void execute()
{
while (true)
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(5000);
} Thread.Sleep(10000);
}
}
}
}在线程循环中把i的值写入到界面上的textBox1中,应该怎么做?
举个最简单的例子:
form:using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;namespace test
{
delegate void AppendInfo(string str);
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
WorkThread wt = new WorkThread();
ThreadStart ts = new ThreadStart(wt.execute); Thread thread = new Thread(ts);
thread.Start();
} public void AppInfo(string str)
{
this.textBox1.Text = this.textBox1.Text + str + "\n";
}
}
}
线程类:using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;namespace test
{
class WorkThread
{
public void execute()
{
while (true)
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(5000);
} Thread.Sleep(10000);
}
}
}
}在线程循环中把i的值写入到界面上的textBox1中,应该怎么做?
//线程类,
public class WorkThread
{
//声明一个事件用于向对象拥有者传递i的值
public delegate void ValueChangedHandler(int i);
public event ValueChanged;
public void execute()
{
while (true)
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(5000);
if(ValueChanged!=null)
{
//触发线程,向外送值
ValueChanged(i);
}
} Thread.Sleep(10000);
}
}
}namespace test
{
delegate void AppendInfo(string str);
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} WorkThread m_workThread = new WorkThread();
public void Form1_Load(object sender,EventArgs e)
{
//使用WorkThread类的线程
m_workThread.ValueChanged = new ValueChangedHandler(WorkThreadValueChanged);
} private void WorkThreadValueChanged(int i)
{
//使用控件的Invoke方法修改控件
this.Invoke(new AppendInfo(new object[]{i.ToString()});
} private void button1_Click(object sender, EventArgs e)
{
ThreadStart ts = new ThreadStart(m_workThread.execute); Thread thread = new Thread(ts);
thread.Start();
} public void AppInfo(string str)
{
this.textBox1.Text = this.textBox1.Text + str + "\n";
}
}
}