110,538
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
namespace StudentInfoMS
{
public partial class thread_2 : Form
{
myThread myThread1, myThread2;
public thread_2()
{
InitializeComponent();
myThread1=new myThread(100,progressBar1);
myThread1.SetForm(this);//这是新加的语句
myThread2=new myThread(200,progressBar2);
myThread2.SetForm(this);//这是新加的语句
}
public class myThread //创建一个线程的类 以便相似的进程都能调用它
{
private thread_2 text; //这里是为了解决“嵌套类里不能使用外部类的非静态成员”而按照网上方法声明的一个外部类的实例 我也不知道正确否
private int SleepTime;
private ProgressBar progressBar;
private Thread thread1;
public myThread(int Time,ProgressBar p1)
{
SleepTime=Time;
progressBar=p1;
thread1=new Thread(new ThreadStart(fun));
thread1.Start();
}
public void SetForm(thread_2 pp)//这是新加的语句
{
this.text= pp;//原先我把这句写到了窗体的构造函数里,可是我又不会调用构造函数,所以相当于白写这句了。现在是写到了方法里,然后在外部类里调用此方法。好像我就差在这儿了!否则早应该成功了!对照3楼的原程序,实际上整个程序我现在改动得非常少!
}
public void fun()
{
while(progressBar.Value!=100)
{
progressBar.Value+=5;
Thread.Sleep(SleepTime);
}
if (this.text.label1.Text == "")
this.text.label1.Text = "第一个线程结束";
else
this.text.label1.Text += ",第二个线程结束";
if (thread1.IsAlive)
thread1.Abort();
}
}
}
}
[quote=引用 31 楼 OrdinaryCoder 的回复:]
[quote=引用 30 楼 weixin_45121425 的回复:]
我基本看懂你的程序和文字解释了:想在内部类里刷新外围类的成员,必须在内部类里创建外围类的实例。你是通过内部类的set方法及在外部类里调用这个方法来创建实例的。这个我理解了。然而有了这个实例this.mainFrom,为啥不能直接写this.mainFrom.textBox1.Text=某字符串?而是通过this.mainFrom.BeginInvoke(new RefreshEventHandle(ShowText));这样的委托来实现呢?不是都有实例了吗? textBox1.Text不就是实例的成员吗? 顺便说一句,我看好多人都会用到Invoke,而我学的那个教程里居然通篇没有这个关键字,愁人,我学的是哪个年代的教程啊?
[quote=引用 26 楼 OrdinaryCoder 的回复:]
[quote=引用 23 楼 正怒月神 的回复:]
[quote=引用 2 楼 eaqpi 的回复:]