Search code examples
.netwpf.net-4.0host-object

WPF host object in new thread


Want to host object not in gui thread, all methods of this object will run in this new thread. Something like that:

Thread thread = new Thread(() =>
{
    MyDataInstance = new MyData();
});

thread.SetApartmentState(ApartmentState.STA);
thread.Start();

But this will not work. Is there any nice way to do it?

(Can create window in other thread, make it invisible, and then host it there, but it seems not the best solution)


Solution

  • You need to call a method that does something. All you are doing with your current code is setting up your data instance.

    So you need to call a method like this:

    Thread thread = new Thread(new ThreadStart(MethodThatDoesStuff)) { MyDataInstance = new MyData(); };
    
    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
    

    MethodThatDoesStuff will have to have a loop so that it continues do to things forever, or have some other control mechanisms (setting up event handlers etc.)