C# calling form.show() from another thread

后端 未结 4 1873
野性不改
野性不改 2020-12-16 10:48

if I call form.show() on a WinForms object from another thread, the form will throw an exception. Is where any way I can add a new, visible form to the main ap

4条回答
  •  感情败类
    2020-12-16 11:47

    If your use case is to display a GUI while the Main GUI Thread is busy (like loading bar) you can do the following:

    private void MethodWithLoadingBar()
    {
        Thread t1 = new Thread(ShowLoading);
        t1.Start();
        // Do the Main GUI Work Here
        t1.Abort();
    }
    
    private void ShowLoading()
    {
        Thread.Sleep(1000); //Uncomment this if you want to delay the display 
                            //(So Loading Bar only shows if the Method takes longer than 1 Second)
        loadingGUI = new LoadingGUI();
        loadingGUI.label1.Text = "Try to Connect...";
        loadingGUI.ShowDialog();
    }
    

    My LoadingGUI is a simple Form with a public Label and a ProgressBar with Style set to Marquee

提交回复
热议问题