委托与线程的新问题
看了你这个代码受益匪浅https://www.daimadog.com/1387.html
但是新问题来了,我尝试把你这个代码合并在同一个类里面成功了,但是我实际的应用是
public delegate void settext(String str);//定义一个用于更新UI的委托,需要传入一个字符串参数
public delegate void threadmethod();//定义一个用于传入线程所运行的方法的委托,不需要参数
class Class1
{
Control constr;//线程依赖对象,一般为窗体上下文
settext mymethod; //线程更新UI的方法,可以通过参数让用户自定义
//第一个窗体上下文,直接传this即可,第二个更新UI的方法名,第三个线程执行的方法名
public void runthread ( Control con, settext menthod ,threadmethod method)
{
constr = con;
mymethod = menthod;
Thread thread = new Thread ( new ThreadStart ( method ) );
thread.IsBackground = true;
thread.Start ();
}
public void add ()//线程需要执行的方法
{
int i = 0;
settext settx = new settext ( getstr );
while (true)
{
i++;
Invoke ( settx, i.ToString () );
Thread.Sleep ( 1000 );
}
}
public partial class Form1 : Form
{
private void button1_Click ( object sender, EventArgs e )
{
//非静态方法,实例化
Class1 mytest = new Class1 ();
mytest.runthread (this,getstr,add);
}
public void getstr (String str)//更新UI方法
{
this.label1.Text = str;
}
}
无论我怎么样改都是报错,第一次用委托,完全摸不到清晰地思路
另外如果我要在Form1里面用另一个按钮来终止这个线程又该如何做呢? 共以下 3 个回答:
改动内容:
mytest.runthread (this,getstr);
public void runthread ( Control con, settext menthod )
Thread thread = new Thread ( new ThreadStart ( add ) );
其实就是把add方法放到了Class1的类中
出错的地方是add方法里面实例化委托语句settext settx = new settext ( getstr );参数中的括号里面的getstr
因为这个方法在Form1的类中,并不在Class1的类中
还有Invoke ( settx, i.ToString () );因为Class1类并不是Form的继承类,所以Invoke无法使用
感谢你的解答
mytest.runthread (this,getstr);
public void runthread ( Control con, settext menthod )
Thread thread = new Thread ( new ThreadStart ( add ) );
其实就是把add方法放到了Class1的类中
出错的地方是add方法里面实例化委托语句settext settx = new settext ( getstr );参数中的括号里面的getstr
因为这个方法在Form1的类中,并不在Class1的类中
还有Invoke ( settx, i.ToString () );因为Class1类并不是Form的继承类,所以Invoke无法使用
感谢你的解答
报什么错呢?初学线程与委托不要看这篇文章,可以分别学习线程与委托。本文是对线程、委托的简单封装。终止线程使用线程对象的Abort方法即可。
所有回复