【发布时间】:2015-10-27 03:50:43
【问题描述】:
我想从 C# VS2013 WPF 中的线程获取返回值。
代码是:
int t = 0;
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
t = myFucntion(myObject) // if I do not use dispatcher, myObject cannot be accessed by the calling thread.
));
return t;
为什么 t 总是 0 而不是返回实际值? 这里的解决方案对我不起作用。
WPF Dispatcher Invoke return value is always null
更新
Application.Current.Dispatcher.Invoke((() =>
{
t = myFunction(myObject));
}));
return t;
但是,t 没有赋值给从 myFunction 返回的实际值。
【问题讨论】:
-
我的猜测是该方法不会等待您的线程。所以它会在你的线程能够将结果存储在
t之前返回0 -
不确定您的意图是在更新任何 UI 项时使用 Dispatcher 对象。您可以移动逻辑来计算
t' either inBackgroudWorker` 或Task并在完成的事件中更新 Dispatch.BeginInvoke 中的 UI 元素(如果有)。 -
@user1672994,如果我不使用dispatcher,调用线程无法访问myObject。
-
请参阅 OP 中的更新。
标签: c# wpf multithreading visual-studio action