我意识到我之前问过一个非常类似的问题,但是我的结构是错误的。我错误地认为我可以在Invoke中执行我的图标生成。这导致了一个不同的问题。不确定如何在线程之间传递对象
我有一个包含500个SVG的文件夹。我想创建文件夹中每个SVG的对象。我需要在单独的线程上执行此操作,因为它可能需要一些时间才能完成,并锁定了UI。
private void Grid_Loaded(object sender, RoutedEventArgs e)
{
Thread t = new Thread(LoadIcons);
t.SetApartmentState(ApartmentState.STA);
t.Start();
}
private void LoadIcons()
{
//Populate ListOfSVGsInFolder
Foreach(String SVGFile in ListOfSVGsInFolder)
{
Icon icon = new Icon
//Perform ~50 lines of code which get the paths and other details from the
//SVGFile and plug them into my icon object
//Now I had a fully generated Icon
//Add the icon to the form
WrapPanel.Children.Add(icon)
}
}
我的问题是我不能将图标添加到WrapPanel。因为我想要在单独的线程上执行此代码,所以我无法直接与UI交谈。不过,我可以这样做:
Foreach(String SVGFile in ListOfSVGsInFolder)
{
Icon icon = new Icon
//Perform ~50 lines of code which get the paths and other details from the
//SVGFile and plug them into my icon object
Dispatcher.Invoke(new Action(() =>
{
WrapPanel.Children.Add(icon);
}));
}
但在这样做,现在我可以不再试图将其添加到WrapPanel当访问我的图标对象。
基本上,我希望能够在文件夹中找到的SVG上执行所有这些计算,在同一个线程中创建SVG的对象,然后将这些对象添加到UI中。
你需要的数据结构(列表/堆栈/ fifo),它由一个线程写入并由另一个线程读取。在访问它之前,你需要锁定()这个结构。 – DrKoch
@DrKoch感谢您的评论。你有任何链接到这个正在申请?我对线程很陌生。 – Ralt
查看更完整的答案 – DrKoch