The calling thread cannot access this object because a different thread owns it.How do i edit the image?

后端 未结 3 1038
情歌与酒
情歌与酒 2020-12-12 01:22

i know there\'s a lot of these type of questions. i wanted to post so that i can share my specific prob because im getting frustrated.

im running a thread which quer

相关标签:
3条回答
  • 2020-12-12 01:45

    As Jon Skeet said, you can use Dispatcher.Invoke to assign the image, but it's not enough, because the BitmapImage has been created on another thread. To be able to use it on the UI thread, you need to Freeze it before:

    logo.Freeze();
    Action action = delegate { image1.Source = logo; };
    image1.Dispatcher.Invoke(action);
    
    0 讨论(0)
  • 2020-12-12 01:54

    You use the Dispatcher associated with the control you want to update:

    Action action = delegate { image1.Source = logo; };
    image1.Dispatcher.Invoke(action);
    

    Note that using Thread.Sleep like this to perform animation is unlikely to give a very good experience... especially as the display thread then has to fetch the URI in order to display the image. It's not going to be very smooth.

    0 讨论(0)
  • 2020-12-12 02:00

    i think this is because you didnt marshal the call to the UI thread. you can do something line this:

    save the context in the constructor,

    // this is a class member variable 
    public readonly SynchronizationContext mySynchronizationContext;
    
    // in ctor
    MySynchronizationContext = SynchronizationContext.Current;
    
    // in your method , to set the image:    
    SendOrPostCallback callback = _=>
    {
      image1.Source = logo;
    };
    
    mySynchronizationContext.Send(callback,null);
    

    by the way, its a good practice to use using statements with the SqlConnection and SqlDataReader. as in:

    using (SqlConnection conn = new SqlConnection("conn string here"))
    {
        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            // db access code
        }
    }
    
    0 讨论(0)
提交回复
热议问题