调用方法直到它的 returns 值
Call method till it returns value
我想调用一个方法,直到它 returns 在我的 WPF
应用程序中成为一个值。
void btnDecode_Click(object sender, RoutedEventArgs e)
{
var task = new Task(task);
task.Start();
task.Wait();
}
async void task()
{
Task<object> result= DecodedResult((BitmapSource)imageBarcode.Source);
object i = await result;
txtBarcodeContent.Text = i.ToString();
}
async Task<object> DecodedResult(BitmapSource renderTargetBitmap)
{
var reader = new BarcodeReader();
txtBarcodeContent.Text = "reading";
return reader.Decode(renderTargetBitmap);
}
但是它在 task.Start();
上抛出了一个错误
"Additional information: The calling thread cannot access this object
because a different thread owns it."
为什么我不能访问它,为什么另一个线程拥有它?
每当您从主线程以外的线程更新 UI 元素时,您需要使用:
this.Dispatcher.Invoke((Action)(() =>
{
...// your code here.
}));
您还可以使用control.Dispatcher.CheckAccess() 来检查当前线程是否拥有控件。如果它确实拥有它,则您的代码看起来很正常。否则,使用上面的模式。
除了 UI 线程之外,这在任何地方都是非法的。
txtBarcodeContent.Text = i.ToString();
而 task.Wait();
破坏了异步效果。
解决方案
点击方法可以async
。
这有效:请注意,当我 await
并且我避免 async void
(Using async without await).
时,我只 async
private async void btnDecode_Click(object sender, RoutedEventArgs e)
{
string result = await DecodedResult((BitmapSource)imageBarcode.Source);
txtBarcodeContent.Text = result;
}
private async Task<string> DecodedResult(BitmapSource renderTargetBitmap)
{
object decoded = await reader.Decode(renderTargetBitmap);
return decoded.ToString();
}
我想调用一个方法,直到它 returns 在我的 WPF
应用程序中成为一个值。
void btnDecode_Click(object sender, RoutedEventArgs e)
{
var task = new Task(task);
task.Start();
task.Wait();
}
async void task()
{
Task<object> result= DecodedResult((BitmapSource)imageBarcode.Source);
object i = await result;
txtBarcodeContent.Text = i.ToString();
}
async Task<object> DecodedResult(BitmapSource renderTargetBitmap)
{
var reader = new BarcodeReader();
txtBarcodeContent.Text = "reading";
return reader.Decode(renderTargetBitmap);
}
但是它在 task.Start();
"Additional information: The calling thread cannot access this object because a different thread owns it."
为什么我不能访问它,为什么另一个线程拥有它?
每当您从主线程以外的线程更新 UI 元素时,您需要使用:
this.Dispatcher.Invoke((Action)(() =>
{
...// your code here.
}));
您还可以使用control.Dispatcher.CheckAccess() 来检查当前线程是否拥有控件。如果它确实拥有它,则您的代码看起来很正常。否则,使用上面的模式。
除了 UI 线程之外,这在任何地方都是非法的。
txtBarcodeContent.Text = i.ToString();
而 task.Wait();
破坏了异步效果。
解决方案
点击方法可以async
。
这有效:请注意,当我 await
并且我避免 async void
(Using async without await).
async
private async void btnDecode_Click(object sender, RoutedEventArgs e)
{
string result = await DecodedResult((BitmapSource)imageBarcode.Source);
txtBarcodeContent.Text = result;
}
private async Task<string> DecodedResult(BitmapSource renderTargetBitmap)
{
object decoded = await reader.Decode(renderTargetBitmap);
return decoded.ToString();
}