Click here to Skip to main content
15,886,069 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
am doing a project in wpf. i navigate from a window to a form and when i navigate to another window it generate the following error.how can i navigate to the other window without error?thanks in advance.

The calling thread must be STA, because many UI components require this

verificationform.cs

C#
if (result.Verified)
            {
                MakeReport("The fingerprint was VERIFIED.");
                Home h = new Home();
                this.Hide();
                h.Show();
            }


==========================================================

C#
public partial class Home : Window
{
    public Home()  ////######error occurs here!!!
    {

        InitializeComponent();
        labelNAME.Content = (string)Application.Current.Properties["name"];
    }
}
Posted
Updated 5-Mar-12 23:01pm
v2
Comments
Sergey Alexandrovich Kryukov 7-Mar-12 2:22am    
Not clear. You need to explain in what thread do you do what (WPF main thread is STA) and where is the exception thrown.
--SA

This code at the bottom worked for me.

Inside an ASP.NET page, I decided to send the exception to the client as a PNG image, but I also got the exception:

"ASP.NET The calling thread must be STA, because many UI components require this."

The 3 thread lines at the bottom is probably what can help you.

C#
/// <summary>
/// Converts an exception to a PNG image, and streams it to the client browser. This helps because
/// the client expects a PNG only. The client viewer doesn't show the image if an error occurred.
/// </summary>
void SendExceptionAsPNG(Exception ex) {

    /* client expects a PNG */
    Thread STAThread = new Thread(() => {

        TextBlock TextBlock = new TextBlock();
        TextBlock.Text = "Internal server error: " + ex.ToString();
        TextBlock.TextWrapping = TextWrapping.WrapWithOverflow;
        TextBlock.Foreground = new SolidColorBrush(System.Windows.Media.Colors.Red);
        TextBlock.VerticalAlignment = VerticalAlignment.Top;

        Border Border = new Border();
        Border.BorderBrush = new SolidColorBrush(System.Windows.Media.Colors.Black);
        Border.BorderThickness = new Thickness(2);
        Border.Margin = new Thickness(20);
        Border.Padding = new Thickness(20);
        Border.Child = TextBlock;
        Border.Width = 700;
        Border.Height = 700;
        Border.Arrange(new Rect(0, 0, 740, 740));

        var RTB = new RenderTargetBitmap(740, 740, 96, 96, PixelFormats.Default);
        RTB.Render(Border);

        var PNGEncoder = new PngBitmapEncoder();
        PNGEncoder.Frames.Add(BitmapFrame.Create(RTB));

        Response.Clear();
        Response.ContentType = "image/png";
        using (MemoryStream MemoryStream = new MemoryStream()) {
            PNGEncoder.Save(MemoryStream);
            byte[] Bytes = MemoryStream.ToArray();
            Response.OutputStream.Write(Bytes, 0, Bytes.Length);
        }
        Response.Flush();
        Response.End();
    });

    STAThread.SetApartmentState(ApartmentState.STA);

    STAThread.Start();

    STAThread.Join();
}


I hope that helps.

Martin
 
Share this answer
 
Comments
Ashish Rathod-.Net Developer 22-Apr-14 3:10am    
Thanks :) .. Your answer is helpful for me .. :)
jespa007 26-Aug-14 6:08am    
It worked!! thanks so much :)!!
Unfortunately, you did't explain what do you do in what thread and where the exception is thrown.

Basically, this is what you can take into account:

Some APIs require STA thread. In particular, the entry point of WPF application (normally, the static method Main is run in the STA thread. If you change the thread to MTA, WPF itself won't work, as it also is based on STA.

If you create some other thread, you can always run it in any of the apartment model, but you cannot change it in a thread itself. You can do in in a thread which you used for creation of other thread, for example:

C#
System.Threading.Thread thread = new System.Threading.Thread(() => {
    // the body of thread method comes here (anonymous in this example, please see below)
    // don't try to change apartment state here
    // but you can call:
    var apartmentState = Thread.System.Threading.Thread.CurrentTread.GetApartmentState();
    // just to check up the apartment state
});
thread.GetApartmentState(System.Threading.ApartmentState.STA);

//...

thread.Start(); // will be executed in specified apartment state


Please see:
http://msdn.microsoft.com/en-us/library/system.threading.thread.aspx[^],
http://msdn.microsoft.com/en-us/library/system.threading.thread.setapartmentstate.aspx[^],
http://msdn.microsoft.com/en-us/library/system.threading.apartmentstate.aspx[^],
http://msdn.microsoft.com/en-us/library/bd9cdfyx.aspx[^].

In real code, you should not probably create threads like that; I've shown this sample only to show how to work with apartment states. I always advise to use thread wrappers, by many good reasons explained in my past solutions where I offer a skeleton classes to wrap threads:
How to pass ref parameter to the thread[^],
change paramters of thread (producer) after it started[^].

—SA
 
Share this answer
 
v3
Comments
vaidyan 7-Mar-12 9:27am    
i have to call(or navigate) to the home window from the verification form. when i do that, as i showed above in the code, i get the error in the line indicated as
////######error occurs here!!! in the home window when creating an object for the home window from the verification page. so i want to navigate to the window from the page and i get the error.....
Sergey Alexandrovich Kryukov 7-Mar-12 18:13pm    
How is it related to STA or MTA apartment state, if related at all?
--SA
vaidyan 11-Mar-12 0:49am    
i don't have much knowledge about apartment states. but when i create an object for the window from a form in wpf, i get the error "The calling thread must be STA, because many UI components require this". so how can i solve this error?
Sergey Alexandrovich Kryukov 12-Mar-12 4:31am    
On this part, I've answered. You can change it the way I explained. Apparently, I cannot say what's wrong in your code presently, as I did not see it.
--SA

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