从DLL调用(Window Runtime组件) [英] Call from DLL (Window Runtime component)

查看:97
本文介绍了从DLL调用(Window Runtime组件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个商店应用程序,我使用DLL中的控件(基于Window Runtime组件)。我的所有View Models都在该DLL中。在该DLL中有定时器,它更新视图(UI)并获得异常从不同的线程调用。我不知道如何解决这个问题。

I have a store application where I am using a control from DLL (Based on Window Runtime component). My all View Models are in that DLL. In that DLL there is timer which updates the view (UI) and get exception "Called from different thread". I am not sure how to resolve this proble.

推荐答案

问题与DLL完全无关,它与使用线程与UI有关。甚至不保证在同一个线程上调用计时器,这就是问题。



你不能从任何其他线程调用当前正在执行的UI的任何方法或属性那么UI线程。为了解决这些问题,有方法 CoreDispatcher.RunAsync 。它使用调用UI线程所需的参数对一些回调进行排队;最终,你的调用将由UI线程执行。这是您可以从其他线程通知UI线程的方法。细节取决于您使用的确切语言和API;请参阅:

http:/ /msdn.microsoft.com/en-us/library/windows/apps/windows.ui.core.coredispatcher.aspx [ ^ ]。



-SA
The problem is totally unrelated to DLL, it is related to the use of the threading with UI. The timer even is not guaranteed to be invoked on the same thread, that's the problem.

You cannot call any method or property of the currently executing UI from any thread other then UI thread. For solving such problems, there is the method CoreDispatcher.RunAsync. It queues some callback with the parameters needed for the call to the UI thread; eventually, you call will be performed by the UI thread. This is the way you can notify the UI thread from other threads. The detail depends on exact language and API you use; please see:
http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.core.coredispatcher.aspx[^].

—SA


private CoreDispatcher _dispatcher = null;

公共事件PropertyChangedEventHandler PropertyChanged;



私有异步任务UIThreadAction(动作行为)

{

await _dispatcher.RunAsync(CoreDispatcherPriority.Normal,()=> act.Invoke() };

}

private async void PropertyChangedAsync(string property)

{

if(PropertyChanged!= null) )

等待UIThreadAction(()=> PropertyChanged(this,new PropertyChangedEventArgs(property)));

}



public FlipViewModel()

{

_dispatcher = Window.Current.Dispatcher;

}



谢谢Sergey Alexandrovich Kryukov
private CoreDispatcher _dispatcher = null;
public event PropertyChangedEventHandler PropertyChanged;

private async Task UIThreadAction(Action act)
{
await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => act.Invoke());
}
private async void PropertyChangedAsync(string property)
{
if (PropertyChanged != null)
await UIThreadAction(() => PropertyChanged(this, new PropertyChangedEventArgs(property)));
}

public FlipViewModel()
{
_dispatcher = Window.Current.Dispatcher;
}

Thanks Sergey Alexandrovich Kryukov


这篇关于从DLL调用(Window Runtime组件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆