create object on another thread

Hi,

I need to be able to create objects on a designated thread. This thread waits and whenever a request comes from another thread, it creates the desired object, and returns it. The objects I need to be created are derived from Form, so it matters on which thread it gets instantiated. So, essentially, the main thread could do something like:

MyForm f = FormsManager.Create(typeof(MyForm));

Where MyForm has a default constructor. Behind the scenes, the Create method switches to the forms thread and instantiates the requested form, and then returns it to the calling thread (all of this, as you see, is transparent).

I need to know how to switch from the main thread to the forms thread, and how to return the result (the created form) back to the calling thread.

Thanks in advance,
Cosmin.


Answer this question

create object on another thread

  • werwin

    Hi,

    IMHO, what you want is Inter-thread communication,

    You will need to use Monitor.Enter, Monitor.Wait, Monitor.Pulse, Monitor.Exit methods to achieve this,

    Please refer the following links for such samples,
    http://www.wilsonmar.com/1threads.htm#ThreadComm
    http://www.codeproject.com/csharp/csthreadmsg.asp (this contains Inter-thread as well as Inter-process communication)
    http://www.dotnetspider.com/kb/Article533.aspx

    HTH,



  • Kieron Lanning

    Hi,

    If you wish to invoke methods from a working thread to the main thread, you will have to use delegation.

    For example lets say that in the Form you have a label that needs to be alerted when something happens in the worker thread.

    So, when that thing occures in the working thread, you need to call a delegate to a method, so that method will change the text for that label.

    I hope this helps.

    guy kolbis



  • BIGuy

    Thank you all for your replies... Manesh was closest in answering what I actually need. I actually want two UI threads, one is the main UI thread, with all the windows and such, and the other one will handle only specific types of windows, which need to be on their own thread (so that if I have a modal window on the main UI thread, I can still access the special windows, click them, move them, etc.).

    Haven't read yet the articles... doing that right now...

  • Sabrecat

    You can switch to the UI thread using the Invoke method on the form class. This will push the request to the UI thread. Note however that once you get the form back you still can't access any of its members because they can only be accessed from the UI thread. Therefore you have really limited the usefulness of this approach.

    Michael Taylor - 1/17/07
    http://p3net.mvps.org


  • create object on another thread