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

后端 未结 3 1037
情歌与酒
情歌与酒 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 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
        }
    }
    

提交回复
热议问题