Click here to Skip to main content
15,889,874 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi,

I have static thread which open new alert window form like below.

C#
public static void ThreadWinForm()
{
    Alert_Window aw = new Alert_Window(); // Alert_Window is winform
    aw.Show();
}


Alert Window is winform created in main application form.

Whenerver I run above thread. Alert window winform open. But hanged. Why?
Is it due to I have created winform instance from different thread. I have even used below method. But no luck.

C#
public static void ThreadWinForm()
{
    Alert_Window aw = new Alert_Window();
    if (aw.InvokeRequired) aw.Invoke((MethodInvoker)delegate()
    {
        aw.Show();
    });
    else
    {
        aw.Show();
    }
}


what is right way to do this?
Posted
Comments
Ziee-M 11-Aug-14 7:32am    
Hi, i am a little confused about this case, since the Alert_Window is created within the thread, using delegate shoulden't be a must.

Here is how i do it using anonymous method, try it just to be sure if the issue is related to the item appertencance.


Alert_Window aw = new Alert_Window();
aw.Invoke((MethodInvoker)delegate
{
aw.Show();
});

if this don't work, then your issue has nothing to do with item appartencance.

Waiting for your response !
Nilesh bhope 12-Aug-14 12:05pm    
Solution given by lukeer is working.

1 solution

You have to ask some UI-Thread element whether or not invoking is required, and let it do the invoking.
That's because you created Alert_Window on another thread. MSDN explains [Control.Invoke] gets a value indicating whether the caller must call an invoke method when making method calls to the control because the caller is on a different thread than the one the control was created on.Change your code to something like
public static void ThreadWinForm()
{
    Alert_Window aw = new Alert_Window();
    if (Form1.InvokeRequired) Form1.Invoke((MethodInvoker)delegate()
    {
        aw.Show();
    });
    else
    {
        aw.Show();
    }
}
With "Form1" being any control that you know lives in the UI thread.
 
Share this answer
 
Comments
Nilesh bhope 12-Aug-14 12:05pm    
Thanks. It's working correctly.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900