简体   繁体   中英

How to spawn a form and not block main thread?

I need to spawn a Form that can be used as usual but the main thread must continue doing whatever it is doing afterwards. When I try the 2 techniques below I can't use the form:

static class Program
{
    private static void spawnForm1()
    {
        new Form1().Show();
    }

    private static void spawnForm2()
    {
        // solved: use ShowDialog() instead of Show() here
        ThreadPool.QueueUserWorkItem(o => { new Form1().Show(); });
    }

    [STAThread]
    static void Main()
    {
        spawnForm1();
        MessageBox.Show("main thread continues");
        // now anything can happen: background processing or start of main form
        // sleeping is just an example for how the form is unresponsive
        Thread.Sleep(30 * 1000);
    }
}

So how can I spawn a simple Form and continue in main thread ? It should respond just like the message box does.

(I can't use Application.Run(...); and I can't use ShowDialog() if it would block the main thread, also: I'm sorry that I have not much reputation but this is not a noob question, I really need it to be spawned like I tried to explain)

Don't create a new thread to show the UI. You're in the UI thread and it should be the one showing the form. Spawn a new thread to do the non-UI work that you want to do instead:

[STAThread]
static void Main()
{
    Task.Run(()=>
        {
            //do non-UI work here
            Thread.Sleep(30 * 1000);
        });
    Application.Run(new Form1());
}

Your code does not work because there is no message loop. You simply must start a message loop for UI elements to function properly. That means at some point you must call Application.Run or Form.ShowDialog .

I see no reason why you cannot use the entry point thread for the UI and then create a worker thread to do whatever else it is you are wanting to happen while the UI is running.

[STAThread]
public static void Main()
{
  Task.Run(() => DoOtherStuff());
  Application.Run(new YourForm());
}

In a comment your wrote:

The main window is ran by application like always. But I need to spawn a window like I described it in both situation existing main window and also without it.

I am assuming you mean that you want to run Form instances on both the entry point thread and a separate thread. My advise is to avoid doing this. It does not work very well. There are a lot of strange things that can happen. Rethink your design so that there is one and only one UI thread. Move any time consuming operations to a worker thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM