问题描述
我总是使用UWP在Xamarin上出现以下错误:
该应用程序调用了一个为其他线程编组的接口。 (来自HRESULT的异常:0x8001010E(RPC_E_WRONG_THREAD))
我要使用:
Xamarin.Forms.BindingBase.EnableCollectionSynchronization(MyList,null,ObservableCollectionCallback);
我不会使用:
Xamarin.Forms.Device.BeginInvokeOnMainThread(()=> MyList.Add(DateTime.Now.ToLongTimeString()));
我有我的理由。
这是非常简单的c#viewmodel代码。您必须将Xamarin项目中的MyList和MainPage中的UWP绑定到ListView:
public class Mainviewmodel : INotifyPropertyChanged
{
public Mainviewmodel()
{
MyList = new ObservableCollection<string>();
Xamarin.Forms.BindingBase.EnableCollectionSynchronization(MyList,null,ObservableCollectionCallback);
Timer timer = new Timer(new TimerCallback(Addtext));
timer.Change(3000,1000);
}
void ObservableCollectionCallback(IEnumerable collection,object context,Action accessMethod,bool writeAccess)
{
lock (collection)
{
accessMethod?.Invoke();
}
}
public void Addtext(object state)
{
MyList.Add(DateTime.Now.ToLongTimeString());
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
if (PropertyChanged != null)
{
PropertyChanged(this,new PropertyChangedEventArgs(propertyName));
}
}
private ObservableCollection<string> MyListValue;
public ObservableCollection<string> MyList
{
get { return MyListValue; }
set
{
MyListValue = value;
OnPropertyChanged();
}
}
这里有人知道我该怎么做吗?
解决方法
在Xamarin BindingBase.EnableCollectionSynchronization中不起作用
问题是您在Addtext
中调用了Timer
。并在un-uithread中触发计时器。如果您不想使用BeginInvokeOnMainThread
,则可以使用Device.StartTimer
来代替Timer
。
Device.StartTimer(TimeSpan.FromSeconds(1),()=> {
Addtext(this);
return true;
} );
并且请检查support列表,EnableCollectionSynchronization无法支持UWP平台。