如何在c#中打开不同线程的winform

时间:2014-06-26 12:08:01

标签: c# multithreading winforms

我想为我的应用做一个简单的“请等待,加载”样式表单。在主要形式中,我准备一张地图和位置。这些准备在加载时会有一些时间。所以我想创建一个新的线程,它将在主窗体的前面打开一个加载表单,以显示“请等待,加载”字符串,可能是动画gif等。但我不能这样做。

我在下面写下了这段代码。

LoadingForm loadingFormInstance;

private void mainForm_Shown(object sender, EventArgs e)
{
     locationLoadingFormThread = new Thread(showLoadingForm);
     locationLoadingFormThread.Start();
}

void showLoadingForm() {
     try
        {
            loadingFormInstance.Show();
        }
        catch (Exception ex)
        {
            string exceptionText = String.Format("{0}:", ex.Message);
            MessageBox.Show(exceptionText);
        } 
    }

从未显示此代码加载表单。有什么不对,我不明白。我做错了什么,但我不明白错。

或任何正确的报价“请等待,加载”样式。

感谢。

1 个答案:

答案 0 :(得分:1)

UI线程阻塞以便显示表单,但是当您在另一个线程上显示它时,它只会显示然后立即消失,因为它不会阻塞。

尝试此操作,启动新的消息循环

private void Login()
{
    Application.Run(new MainPage());
}

private void loginBtn_Click(object sender, EventArgs e)
{
    Thread customInstallThread = new Thread(Login);
    customInstallThread.SetApartmentState(ApartmentState.MTA);
    customInstallThread.IsBackground = true;
    customInstallThread.Start();
}