PropertyChangedEventHandler不是异步触发

时间:2017-12-15 14:34:02

标签: c# wpf

我已经实现了这个属性来隐藏和显示一个元素:

private bool isWorking = false;

public bool IsWorking {
    get {
        return this.isWorking;
    }

    set {
        this.isWorking = value;
        OnPropertyChanged("IsWorking");
    }
}

public event PropertyChangedEventHandler PropertyChanged;

protected void OnPropertyChanged(string name)
{
    PropertyChangedEventHandler handler = PropertyChanged;
    if (handler != null)
    {
        handler(this, new PropertyChangedEventArgs(name));
    }
}

但是当我更改属性时,即使该方法是异步的,它也会以同步方式进行更改。

你能解释一下如何解决这个问题吗?我试图在更改的属性或代码中移动调度程序事件,但它不起作用!

1 个答案:

答案 0 :(得分:0)

您可能希望拥有一个async Click事件处理程序,如下所示:

private async void Button_Click(object sender, RoutedEventArgs e)
{
    viewModel.IsWorking = true;

    await Task.Run(() =>
    {
       // do some long processing
    });

    viewModel.IsWorking = false;
}

或视图模型中的异步方法

public async Task DoSomeProcessing()
{
    IsWorking = true;

    await Task.Run(() =>
    {
       // do some long processing
    });

    IsWorking = false;
}

从异步点击处理程序调用,如

private async void Button_Click(object sender, RoutedEventArgs e)
{
    await viewModel.DoSomeProcessing();
}