【发布时间】:2013-11-22 16:55:47
【问题描述】:
我对 WPF 和 WPF 中的线程非常陌生,并且已经成功地在我的程序中实现了 bing 地图控件。问题是,控件需要很长时间才能加载,并且在打开程序时会减慢程序本身的速度。加载时间从大约 2 秒增加到大约 20 秒,这实在是不能接受。
我的想法是,将 bing 地图控件加载到单独的线程中,因此不会降低性能。我一直在尝试这样做,但是我的 UI 一直被地图控件的加载过程阻塞。
这是一个使用 Dispatcher 的示例:
private init()
{
Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(delegate()
{
// Background thread: I would like to load the map here
Map map = new Map();
map.CredentialsProvider = providerKey;
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
new Action(() =>
{
// Back to the UI thread
// How do I assign the loaded Map to this thread?
mapElementOnUI = map;
mapPanel.Children.Add(mapElementOnUI);
}));
}
));
thread.Start();
//Load the rest of the GUI here
}
如果我这样处理线程,我会得到一个 InvalidOperationException(无 STA 线程)。如果我将代码更改为以下代码,我的 UI 在加载地图控件时会阻塞:
private init()
{
Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(delegate()
{
// Background thread
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
new Action(() =>
{
// Back to the UI thread
mapElementOnUI = new Map();
mapElementOnUI.CredentialsProvider = providerKey;
mapPanel.Children.Add(mapElementOnUI);
}));
}
));
thread.Start();
//Load the rest of the GUI here
}
我也一直在尝试通过 await 和 async 实现解决方案,但没有成功。是否可以在单独的线程中加载地图控件?有人可以用一段代码帮我解决这个问题吗?非常感谢!
【问题讨论】:
标签: c# wpf multithreading bing-maps