Make Predicate从异步方法C#返回一个bool值

时间:2016-10-17 05:31:36

标签: c# .net async-await predicate

如何让Predicate从异步方法C#

返回bool值
private void OnFilterTextBoxTextChangedHandler(object oSender, TextChangedEventArgs oArgs)
{
 //Other operations
 _oCollectionView.Filter = new Predicate<object>(DoFilter); //wrong return type
}

退货方法

private async Task<bool> DoFilter(object oObject)
{
    if (_sFilterText == "")
    {
        return true;
    }
    return false;
}

1 个答案:

答案 0 :(得分:0)

Predicate<T>是代表。在向CollectionView添加过滤器时,无需实例化新谓词。相反,您可以像这样添加过滤器:

_oCollectionView.Filter = DoFilter;

其次,CollectionView.Filter委托的签名是public delegate bool Predicate<object>(object obj)。参数obj是正在评估的CollectionView的元素。您无法更改此签名以使其异步。

在您的示例中,我将考虑执行以下操作:

constructor()
{
    InitializeComponent();
    // Alternatively put this in an initialization method.
    _oCollectionView.Filter = DoFilter;
}

private async void OnFilterTextBoxTextChangedHandler(object oSender, TextChangedEventArgs oArgs)
{
    // Other operations

    // Asynchronous processing
    await SetupFilterAsync();
    _oCollectionView.Refresh();
}

private async Task SetupFilterAsync()
{
    // Do whatever you need to do async.
}

private bool DoFilter(object obj)
{
    // Cast object to the type your CollectionView is holding
    var myObj = (MyType) obj;
    // Determine whether that element should be filtered
    return myObj.ShouldBeFiltered;
}

您还可以将过滤器定义为lambda,它看起来像这样并消除DoFilter方法:

_oCollectionView.Filter = x => ((MyType)x).ShouldBeFiltered;