我制作了一个创建线程并在该线程中创建图像的程序:
private async void GetCamera()
{
....
tk = new Task(MyAwesomeTask);
tk.Start();
}
private async void MyAwesomeTask()
{
while (true)
{
await Task.Delay(TimeSpan.FromSeconds(0.5));
SavePhoto1();
}
}
private void SavePhoto1()
{
try
{
WriteableBitmap wb1 = new WriteableBitmap(320, 240);//throw exception
}catch (Exception ee)
{
String s = ee.ToString();
}
}
但是行
WriteableBitmap wb1 = new WriteableBitmap(320, 240);
抛出异常:
s="System.Exception: The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))\r\n at Windows.UI.Xaml.Media.Imaging.WriteableBitmap..ctor(Int32 pixelWidth, Int32 pixelHeight)\r\n at TestVideo.MainPage.SetImageFromStream() in ...\MainPage.xaml.cs:line 500\r\n at TestVideo.MainPage.SavePhoto1() in ....\MainPage.xaml.cs:line 145"
我需要做什么?
请您参考如下方法:
第一个问题是您正在使用async void。只有在方法是事件处理程序时才应该这样做。在您的情况下,您应该改用 async Task:
private async Task GetCamera()
{
....
//tk = new Task(MyAwesomeTask);
//tk.Start();
await Task.Run(async () => await MyAwesomeTask());
...
}
private async Task MyAwesomeTask()
{
while (true)
{
await Task.Delay(TimeSpan.FromSeconds(0.5));
// added await
await SavePhoto1();
}
}
您实际上不需要在上述方法中返回一个Task。编译器会自动为您执行此操作。
要解决您的问题,您应该只在 UI 线程上创建 WriteableBitmap 对象。你可以这样做:
private async Task SavePhoto1()
{
try
{
WriteableBitmap wb1 = null;
await ExecuteOnUIThread(() =>
{
wb1 = new WriteableBitmap(320, 240);//throw exception
});
// do something with wb1 here
wb1.DoSomething();
}catch (Exception ee)
{
String s = ee.ToString();
}
}
public static IAsyncAction ExecuteOnUIThread(Windows.UI.Core.DispatchedHandler action)
{
return Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, action);
}
我没有通过编译来测试上面的内容,但它应该会给你一个良好的开端。如果您有任何问题,请告诉我。
