简体   繁体   English

C#WPF多线程无法从VS2013中的Dispatcher.BeginInvoke返回实际值

[英]C# WPF multithreading cannot return the actual value from Dispatcher.BeginInvoke in VS2013

I would like to get the return value from a thread in C# VS2013 WPF. 我想从C#VS2013 WPF中的线程获取返回值。

The code is: 代码是:

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;

Why t is always 0 and not return the actual value ? 为什么t总是为0而不返回实际值? The solution here does not work for me. 这里的解决方案对我不起作用。

WPF Dispatcher Invoke return value is always null WPF Dispatcher Invoke返回值始终为null

UPDATE 更新

Application.Current.Dispatcher.Invoke((() =>
        {
          t = myFunction(myObject));
        }));
return t;

But, t is not assigned to the actual value returned from myFunction. 但是,t未分配给myFunction返回的实际值。

Dispatcher.BeginInvoke is asynchronous. Dispatcher.BeginInvoke是异步的。 It will return immediatly after queuing the delegate to the message loop: 将委托排队到消息循环后,它将立即返回:

Executes the specified delegate asynchronously at the specified priority on the thread the Dispatcher is associated with. 在与Dispatcher关联的线程上以指定的优先级异步执行指定的委托。

That means that you have a race-condition, and you might even see t actually contain the expected value if you run it enough times. 这意味着您有一个竞争条件,如果您运行了足够的时间,您甚至可能会看到t实际上包含期望值

To eliminate that, If you want to wait until the delegate is ran on the message loop, use Dispatcher.Invoke instead: 为了消除这种情况,如果要等到委托在消息循环上运行,请改用Dispatcher.Invoke

Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, 
                                      new Action(() => t = myFunction()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM