简体   繁体   中英

Different instancens in a thread, or threadpool?

I currently have a project that starts up a central logic class (which uses some other .dll's to check on hardware or connect to the database). After that, a WPF form is started. This form uses the information of the central logic.

Currently, the application is being started like this:

public void StartTheWholeBunch()
{
    Thread thread = new Thread(() =>
    {
        applicationLogic = new ApplicationLogic();
        Application app = new Application();
        app.Run(new MainWindow(applicationLogic));
    });
    thread.IsBackground = true;
    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
    thread.Join();
}

The MainWindow is one of the two WPF applications I want to use. So a second one will join in the fun oa later stage.

The current setup is working. Everything communicates with each other and stuff, no problems here. I was just wondering if the use of this Thread is correct. When I leave applicationLogic = new ApplicationLogic(); out of the Thread, things are bound to go wrong (for example with creating MessageBox popups, the whole application will freeze here).

Should I keep everything in one thread here? Or is it a better practice to split everything up and/or create a Threadpool? How can I approach that the best way?

The applicationLogic is supposed to run indefinitely.

I think you're mixing the need for a globally existent class instance and threads. You don't need a separate thread for this, you just need ApplicationLogic to be a Singleton.

public class ApplicationLogic
{
    private static ApplicationLogic _instance = new ApplicationLogic();
    public static ApplicationLogic Instance { get { return _instance; } }

    private ApplicationLogic() { }
}

Further, by performing an immediate thread.Join(); , you're making the Thread a moot point. You don't need this thread, just start up the main form. And if you wanted to load another form, just do it, create a new instance and show it:

var otherForm = new OtherForm();
otherForm.Show();

and so now that we are making ApplicationLogic a Singleton , which is what you were doing with the other thread (kind of), you can just access it like this:

ApplicationLogic.Instance.DoSomething();

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