【问题标题】:Make Predicate return a bool value from async method C#使谓词从异步方法 C# 返回一个布尔值
【发布时间】:2016-10-17 05:31:35
【问题描述】:

如何使 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;
}

【问题讨论】:

  • 您的DoFilter 不是async 方法。它缺少await
  • 即使DoFilter方法中有await,DoFilter方法也没有被等待iteslf,所以返回类型仍然是Task对吧?
  • @DovydasSopa 即使我让它等待它也不能解决我的问题。
  • @MaxHampton 是的,它仍然是任务
  • @user6384353 我只是说这段代码不正确。这是你的完整代码吗?如果是这样,为什么需要oObject 作为参数?如果没有,也许你想分享你的完整代码?

标签: c# .net async-await predicate


【解决方案1】:

Predicate&lt;T&gt; 是代表。向 CollectionView 添加过滤器时,不需要实例化新谓词。相反,您可以像这样添加过滤器:

_oCollectionView.Filter = DoFilter;

其次,CollectionView.Filter 委托的签名是public delegate bool Predicate&lt;object&gt;(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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多