一个关于线程挂起的问题
问题是这样的,项目中有两个窗口,一个Form1,一个Form2,在Form1和Form2中各有一个按钮,在按钮的click事件中生成了Form2的一个实例frm2,用Show方法,注意不是ShowDialog方法,本意是调用完Show方法之后把Form1的线程挂起,在frm2这个窗口中的按钮click事件中把Form1的线程调用Resume方法之后继续,之后再继续执行Show方法之后的语句,写了个很简单的测试代码,如下:
namespace WinAppThreadSuspendTest{ public partial class Form1 : Form { private static Thread currentThread; public static Thread CurrentThread { get { return currentThread; } } public Form1() { InitializeComponent(); InitCurrentThread(); } private static void InitCurrentThread() { currentThread = Thread.CurrentThread; } private void button1_Click(object sender, EventArgs e) { Form2 frm2 = new Form2(); frm2.Show(); currentThread.Suspend(); MessageBox.Show("Suspended thread resume"); } }}
namespace WinAppThreadSuspendTest{ public partial class Form2 : Form { public Form2() { InitializeComponent(); } private void btnOK_Click(object sender, EventArgs e) { Form1.CurrentThread.Resume(); this.Close(); } }}
private static Thread MainThread; private static Frm_Login3 LoginForm; private static bool pass = false; public static Form ShowLoginForm(Type MainFormType, string description) { Form f = null; MainThread = Thread.CurrentThread; Thread t2 = new Thread(new ParameterizedThreadStart(CreateLoginForm));//创建登录线程 t2.Start(description);//启动登录线程 try { MainThread.Join();//挂起主线程,登录成功后在登录窗体上调用 MainThread.Interrupt();恢复主线程 } catch { } if (pass)//pass:是否登录成功 { try { f = (Form)Activator.CreateInstance(MainFormType);//创建主窗体 LoginForm.Invoke(new MethodInvoker(CloseLoginForm));//关闭登录窗体 } catch(Exception ex) { gt.WinForm.ShowMessage.Error(ex); f = null; } } return f; } private static void CloseLoginForm() { LoginForm.Close(); } private static void CreateLoginForm(object obj) { LoginForm = new Frm_Login3(); LoginForm.Description = obj.ToString(); LoginForm.ShowDialog(); }