简体   繁体   中英

How to access & use an object which has been created on a different thread in WPF

I am having following scenario that I need to show preview option in my application like what ms-word does. When we click the info option under File menu item, then preview of document is shown.

In the same way, I also want to show the preview of my data rendering part in my application when someone clicks File\\Info panel. For this i have written a method which gets the preview or screenshots of my app but that method is taking some time So when somebody click on the File menu then application hangs for a while. So, i tried to call that method on different thread using background worker as well as normal thread mechanism. but the thing is that method I am calling on different thread it returns an image source object and when I try to access that object on run worker completed event of background worker, then it shows an exception like owner of this object is a different thread which means that returned image has been created on a different thread therefore I can't use it. So, what is the optimized way to get and use that image in my case.

Code tends to be like this.

    public void ShowPreview()
   {
      ImageSource source =null;
      var bgWorkerThread = new BackgroundWorker()
       bgWorkerThread.DoWork +=(SENDER,ARGS)=> {
                                                 source = planView.GetPreviewImage();
                                                }
       bgWorkerThread.RunWorkerCompleted += (sender,args)=>
 {
    // Application crashes at this point 
    infoPanel.PreviewImage.source = args.Result as ImageSource;
  }
   } 

you can use invoke or you could create a "storage class" (i think its called a singleton but I'm not sure) reuse the same instance across several classes and/or threads like this.

class Test
{
    void main()
    {
        newThread nt = new newThread();
        Storage store = new Storage();
        nt.store = store;
        Thread t = new Thread(new ThreadStart(nt.runMe));
        t.Start();
    }
}
public class newThread
{
    public Storage store;
    public void runMe()
    {
        store.someNum = 8;
    }
}
public class Storage
{
    public int someNum;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM