ReactiveUI 调用线程不能访问这个对象,因为另一个线程拥有它 [英] ReactiveUI The calling thread cannot access this object because a different thread owns it
本文介绍了ReactiveUI 调用线程不能访问这个对象,因为另一个线程拥有它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我在后面的代码中使用绑定,单击更改 IsBusy 后会出现错误
If I use a binding in code behind, getting an error after click at change IsBusy
"The calling thread cannot access this object because a different thread owns it"
xml:
<Button x:Name="AsyncCommand"
Height="20"
Content="PushAsync"/>
<ProgressBar x:Name="IsBusy"
Height="20"/>
CS:
this.Bind(ViewModel, x => x.IsBusy, x => x.IsBusy.IsIndeterminate);
this.BindCommand(ViewModel, x => x.AsyncCommand, x => x.AsyncCommand);
视图模型:
public class TestViewModel : ReactiveObject
{
public TestViewModel()
{
AsyncCommand = new ReactiveAsyncCommand();
AsyncCommand
.RegisterAsyncFunction(x =>
{ IsBusy = true; Thread.Sleep(3000); return "Ok"; })
.Subscribe(x => { IsBusy = false; });
}
private bool isBusy;
public bool IsBusy
{
get { return isBusy; }
set { this.RaiseAndSetIfChanged(x => x.IsBusy, ref isBusy, value); }
}
public ReactiveAsyncCommand AsyncCommand { get; protected set; }
}
但是,如果我在 xaml 中进行绑定,则一切正常,如下所示:
But if I make a bind in xaml all works, like this:
CS:
DataContext = new TestViewModel();
xml:
<Button x:Name="AsyncCommand"
Height="20"
Content="PushAsync"
Command="{Binding AsyncCommand}"/>
<ProgressBar x:Name="IsBusy"
Height="20"
IsIndeterminate="{Binding IsBusy}"/>
为什么会这样?
推荐答案
试试这个:
public TestViewModel()
{
AsyncCommand = new ReactiveAsyncCommand();
AsyncCommand.Subscribe(_ => IsBusy = true);
AsyncCommand
.RegisterAsyncFunction(x =>
{ Thread.Sleep(3000); return "Ok"; })
.Subscribe(x => { IsBusy = false; });
}
甚至更好:
ObservableAsPropertyHelper<bool> _IsBusy;
public bool IsBusy {
get { return _IsBusy.Value; }
}
public TestViewModel()
{
AsyncCommand = new ReactiveAsyncCommand();
AsyncCommand
.RegisterAsyncFunction(x =>
{ Thread.Sleep(3000); return "Ok"; })
.Subscribe(x => { /* do a thing */ });
AsyncCommand.ItemsInFlight
.Select(x => x > 0 ? true : false)
.ToProperty(this, x => x.IsBusy);
}
这篇关于ReactiveUI 调用线程不能访问这个对象,因为另一个线程拥有它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文