[英]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. 我遇到以下情况,我需要像ms-word一样在应用程序中显示预览选项。 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. 您可以使用invoke或创建一个“存储类”(我认为它称为单例,但我不确定)可以在多个类和/或此类线程中重用同一实例。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.