如何在 C# 应用程序中切换主线程
本文关键字:线程 应用程序 | 更新日期: 2023-09-27 18:36:56
如何分离线程?
我使用实例来运行LoginForm.cs首先,所以我在应用程序中的第一个线程是LoginForm.cs文件,但是我不想再运行LoginForm.cs的线程了,登录成功后,我希望我的应用程序在MainInterface中运行主线程.cs,这意味着,第一个线程运行LoginForm.cs,然后在LoginForm.cs上停止Thread,登录更正后,线程在MainInterface.cs中运行。
我遵循以下代码,但登录表单.cs仍然是一个主线程:
主界面.cs
using System;
public class MainInterface : Form
{
private static MainInterface Current;
private MainInterface ()
{
if ( LoginForm.Instance != null )
LoginForm.Instance.Close ();
}
public static MainInterface Instance
{
get
{
if (Current == null)
{
Current = new MainInterface ();
}
return Current;
}
}
}
登录表单.cs
using System;
public class LoginForm: Form
{
private static LoginForm Current;
private LoginForm ()
{
if ( MainInterface.Instance != null )
MainInterface.Instance.Close ();
}
public static LoginForm Instance
{
get
{
if (Current == null)
{
Current = new LoginForm ();
}
return Current;
}
}
}
程序.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace Myapp
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
LoginForm.Instance.ShowDialog ();
}
}
}
程序.cs
using (Login login = new Login())
{
login.ShowDialog(); //Close this form after login is correct in login form button_click
}
if (isValiduser == true) //Static variable created in application to check user
{
Application.Run(new MainInterface());
}
登录表单点击事件
private void btnLogin_Click(object sender, EventArgs e)
{
if(isValiduser == true)
{
this.Close();
}
else
{
//else part code
}
}