C# 从TimerCallback功能Windows Phone 8更新UI线程
这里有点难住了 我有一个TimerCallback,每10秒发射一次,其中包含要放在地图上的地质点。我尝试从计时器回调函数中将这些添加到映射中,但是由于它位于不同的线程中,因此无法执行此操作。我收到以下错误: 在中发生“System.IO.FileNotFoundException”类型的异常 mscorlib.ni.dll,在托管/本机边界之前未进行处理 “System.UnauthorizedAccessException”类型的首次意外异常 发生在System.Windows.ni.dll中 我怎样才能避免这种情况?我想也许添加一个NotifyCollectionChanged监听器可以工作,但是我仍然有同样的问题。代码如下所示C# 从TimerCallback功能Windows Phone 8更新UI线程,c#,multithreading,windows-phone-8,C#,Multithreading,Windows Phone 8,这里有点难住了 我有一个TimerCallback,每10秒发射一次,其中包含要放在地图上的地质点。我尝试从计时器回调函数中将这些添加到映射中,但是由于它位于不同的线程中,因此无法执行此操作。我收到以下错误: 在中发生“System.IO.FileNotFoundException”类型的异常 mscorlib.ni.dll,在托管/本机边界之前未进行处理 “System.UnauthorizedAccessException”类型的首次意外异常 发生在System.Windows.ni.dll
private ObservableCollection<Bus> _busList;
private Timer _timer = null;
public ItemViewModel route;
public ObservableCollection<Bus> BusList
{
get { return _busList; }
set { _busList = value; }
}
//public LocationManager locMan = LocationManager.Instance;
// Constructor
public DetailsPage()
{
InitializeComponent();
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
// When page is navigated to set data context to selected item in list
protected override void OnNavigatedTo(NavigationEventArgs e)
{
route = null;
if (DataContext == null)
{
string selectedIndex = "";
if (NavigationContext.QueryString.TryGetValue("selectedItem", out selectedIndex))
{
int index = int.Parse(selectedIndex);
DataContext = App.ViewModel.Items[index];
route = App.ViewModel.Items[index];
if (_timer == null)
{
TimerCallback tcb = obtainJSON;
_timer = new Timer(tcb, route.RouteID, 0, 10000);
}
else
{
_timer.Change(0, 10000);
}
if (BusList == null)
{
BusList = new ObservableCollection<Bus>();
}
else
{
BusList.Clear();
}
BusList.CollectionChanged += HandleBusAdded;
}
}
}
private void HandleBusAdded(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Reset)
{
Debug.WriteLine("Everything was cleared");
}
else
{
foreach (Bus item in e.NewItems)
{
Debug.WriteLine(item.vehicleID);
Polygon polygon = new Polygon();
polygon.Points.Add(new Point(0, 0));
polygon.Points.Add(new Point(0, 75));
polygon.Points.Add(new Point(25, 0));
polygon.Fill = new SolidColorBrush(Colors.Blue);
// Create a MapOverlay and add marker
MapOverlay overlay = new MapOverlay();
overlay.Content = polygon;
overlay.GeoCoordinate = new GeoCoordinate(item.lat, item.lng);
overlay.PositionOrigin = new Point(0.0, 1.0);
MapLayer mapLayer = new MapLayer();
mapLayer.Add(overlay);
//mapView.Layers.Add(mapLayer);
this.Dispatcher.BeginInvoke(() =>
{
mapView.Layers.Add(mapLayer);
});
}
}
}
public void obtainJSON(Object stateInfo)
{
string url = "http://xxx.xxx.xxx" + stateInfo.ToString();
var client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Decrypt);
client.DownloadStringAsync(new Uri(url));
}
public void Decrypt(Object sender, DownloadStringCompletedEventArgs e)
{
if (BusList.Count > 0)
{
BusList.Clear();
}
if (!e.Cancelled && e.Error == null)
{
var temp = new List<string>();
string[] buses = e.Result.Split('\n');
foreach (string bus in buses)
{
if (!string.IsNullOrWhiteSpace(bus) && !string.IsNullOrEmpty(bus))
{
temp.Add(bus);
}
}
foreach (string item in temp)
{
string[] busInfo = item.Split(',');
Bus newBus = new Bus(busInfo[0], busInfo[1], busInfo[2]);
BusList.Add(newBus);
}
// This is where I initially tried
/*Polygon polygon = new Polygon();
polygon.Points.Add(new Point(0, 0));
polygon.Points.Add(new Point(0, 75));
polygon.Points.Add(new Point(25, 0));
polygon.Fill = new SolidColorBrush(Colors.Blue);
// Enable marker to be tapped for location information
// polygon.Tag = new GeoCoordinate(BusList[0].lat, BusList[0].lng);
// Create a MapOverlay and add marker
MapOverlay overlay = new MapOverlay();
overlay.Content = polygon;
overlay.GeoCoordinate = new GeoCoordinate(BusList[0].lat, BusList[0].lng);
overlay.PositionOrigin = new Point(0.0, 1.0);
MapLayer mapLayer = new MapLayer();
mapLayer.Add(overlay);
this.Dispatcher.BeginInvoke(() =>
{
mapView.Layers.Add(mapLayer);
});*/
Debug.WriteLine("Present buses " + BusList[0].vehicleID + ", " + BusList[1].vehicleID);
}
}
}
private observeCollection\u busList;
专用定时器_Timer=null;
公共项目视图模型路径;
公共可观察收集总线列表
{
获取{return\u busList;}
设置{u busList=value;}
}
//public LocationManager locMan=LocationManager.Instance;
//建造师
公共详情
{
初始化组件();
//本地化ApplicationBar的示例代码
//BuildLocalizedApplicationBar();
}
//导航页面以将数据上下文设置为列表中的选定项时
受保护的覆盖无效OnNavigatedTo(NavigationEventArgs e)
{
路由=空;
if(DataContext==null)
{
字符串selectedIndex=“”;
if(NavigationContext.QueryString.TryGetValue(“selectedItem”,out selectedIndex))
{
int index=int.Parse(selectedIndex);
DataContext=App.ViewModel.Items[索引];
路由=App.ViewModel.Items[索引];
如果(_timer==null)
{
TimerCallback tcb=获取JSON;
_定时器=新定时器(tcb,route.RouteID,0,10000);
}
其他的
{
_计时器。更改(0,10000);
}
如果(总线列表==null)
{
BusList=新的ObservableCollection();
}
其他的
{
BusList.Clear();
}
BusList.CollectionChanged+=添加把手;
}
}
}
已添加私有无效句柄(对象发送方,NotifyCollectionChangedEventArgs e)
{
if(e.Action==NotifyCollectionChangedAction.Reset)
{
Debug.WriteLine(“一切都已清除”);
}
其他的
{
foreach(e.NewItems中的总线项)
{
调试写入线(项目vehicleID);
多边形=新多边形();
polygon.Points.Add(新点(0,0));
polygon.Points.Add(新点(0,75));
polygon.Points.Add(新点(25,0));
polygon.Fill=新的SolidColorBrush(Colors.Blue);
//创建MapOverlay并添加标记
MapOverlay=新的MapOverlay();
覆盖。内容=多边形;
overlay.GeoCoordinate=新的GeoCoordinate(item.lat,item.lng);
叠加位置原点=新点(0.0,1.0);
MapLayer MapLayer=新的MapLayer();
添加(覆盖);
//mapView.Layers.Add(mapLayer);
this.Dispatcher.BeginInvoke(()=>
{
mapView.Layers.Add(mapLayer);
});
}
}
}
public void获取JSON(对象状态信息)
{
字符串url=”http://xxx.xxx.xxx“+stateInfo.ToString();
var client=new WebClient();
client.DownloadStringCompleted+=新的DownloadStringCompletedEventHandler(解密);
DownloadStringAsync(新Uri(url));
}
公共无效解密(对象发送方,下载StringCompletedEventArgs e)
{
如果(BusList.Count>0)
{
BusList.Clear();
}
如果(!e.Cancelled&&e.Error==null)
{
var temp=新列表();
字符串[]总线=e.Result.Split('\n');
foreach(总线中的字符串总线)
{
如果(!string.IsNullOrWhiteSpace(总线)和&!string.IsNullOrEmpty(总线))
{
温度添加(总线);
}
}
foreach(临时文件中的字符串项)
{
字符串[]busInfo=item.Split(',');
总线新总线=新总线(busInfo[0],busInfo[1],busInfo[2]);
总线列表。添加(新总线);
}
//这就是我最初尝试的地方
/*多边形=新多边形();
polygon.Points.Add(新点(0,0));
polygon.Points.Add(新点(0,75));
polygon.Points.Add(新点(25,0));
polygon.Fill=新的SolidColorBrush(Colors.Blue);
//允许轻触标记以获取位置信息
//polygon.Tag=新地理坐标(总线列表[0].lat,总线列表[0].lng);
//创建MapOverlay并添加标记
MapOverlay=新的MapOverlay();
覆盖。内容=多边形;
overlay.GeoCoordinate=新的地理坐标(总线列表[0]。lat,总线列表[0]。lng);
叠加位置原点=新点(0.0,1.0);
MapLayer MapLayer=新的MapLayer();
添加(覆盖);
this.Dispatcher.BeginInvoke(()=>
{
mapView.Layers.Add(mapLayer);
});*/
Debug.WriteLine(“当前总线”+总线列表[0]。车辆ID+,“+总线列表[1]。车辆ID”);
}
}
}
最简单的方法是将获取JSON
方法中发生的事情封装在一个匿名函数中,该函数被发送回UI线程:
public void obtainJSON(Object stateInfo)
{
Dispatcher.BeginInvoke(() => {
string url = "http://xxx.xxx.xxx" + stateInfo.ToString();
var client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Decrypt);
client.DownloadStringAsync(new Uri(url));
});
}
这将意味着一切(都使网络成为现实)