先把代码贴出来Form1.csnamespace TransferValue
{
public partial class Form1 : Form
{
public Class1 class1;
Thread thread; public Form1()
{
InitializeComponent();
class1 = new Class1();
} private void button1_Click(object sender, EventArgs e)
{
thread = new Thread(new ThreadStart(class1.ChangeValue));
thread.Start();
Form2 frm2 = new Form2(class1);
//class1.ChangeValue();
frm2.Show();
}
}
}
------------------------------------------------------------------------------
Form2.csnamespace TransferValue
{
public partial class Form2 : Form
{
public Form2(Class1 class1)
{
InitializeComponent();
Form2.CheckForIllegalCrossThreadCalls = false;
class1.fevent += new Class1.f(this.ShowValue);
}
public void ShowValue(int i)
{
textBox1.Text = i.ToString();
}
}
}
-------------------------------------------------
Class1.csnamespace TransferValue
{
public class Class1
{
public delegate void f(int i);
public event f fevent; public void ChangeValue()
{
Random r = new Random();
int value = r.Next(10);
if (fevent != null)
{
fevent(value);
}
}
}
}
----------------------------------------------------------------------
程序运行后,即显示Form1 窗体,点击上面的按钮,弹出Form2窗体,此时我希望能够在Form2窗体中的文本框中显示Class1中设定的值。
问题在于 要连续打开2个以上的Form2 ,最新打开的Form2文本框中没有值,但其他的Form2中都是同一个值。
不用线程的话,可以显示。但是我希望用到线程。因为这个程序是仿照另一个大程序写的,问题都是一样的。
------------------------------------------------
谁感兴趣的话,我把完整的代码都发过来。谢谢
{
public partial class Form1 : Form
{
public Class1 class1;
Thread thread; public Form1()
{
InitializeComponent();
class1 = new Class1();
} private void button1_Click(object sender, EventArgs e)
{
thread = new Thread(new ThreadStart(class1.ChangeValue));
thread.Start();
Form2 frm2 = new Form2(class1);
//class1.ChangeValue();
frm2.Show();
}
}
}
------------------------------------------------------------------------------
Form2.csnamespace TransferValue
{
public partial class Form2 : Form
{
public Form2(Class1 class1)
{
InitializeComponent();
Form2.CheckForIllegalCrossThreadCalls = false;
class1.fevent += new Class1.f(this.ShowValue);
}
public void ShowValue(int i)
{
textBox1.Text = i.ToString();
}
}
}
-------------------------------------------------
Class1.csnamespace TransferValue
{
public class Class1
{
public delegate void f(int i);
public event f fevent; public void ChangeValue()
{
Random r = new Random();
int value = r.Next(10);
if (fevent != null)
{
fevent(value);
}
}
}
}
----------------------------------------------------------------------
程序运行后,即显示Form1 窗体,点击上面的按钮,弹出Form2窗体,此时我希望能够在Form2窗体中的文本框中显示Class1中设定的值。
问题在于 要连续打开2个以上的Form2 ,最新打开的Form2文本框中没有值,但其他的Form2中都是同一个值。
不用线程的话,可以显示。但是我希望用到线程。因为这个程序是仿照另一个大程序写的,问题都是一样的。
------------------------------------------------
谁感兴趣的话,我把完整的代码都发过来。谢谢
线程同步的问题
ps:是否可以不用多线程呢
frm2.Show(); thread.Start();
可以解决那个问题