linq查询中的异步任务方法问 题在c#中返回

问题描述 投票:0回答:1

我需要帮助处理异步任务我试图返回来自数据库的值列表,我有一个表存储库,然后使用该类的irepository,我遇到的问题是在我的方法中使用我的异步任务返回值列表。

这是我的代码,我的问题是如何正确使用异步任务,然后在方法中返回我的linq查询,因为我得到一个错误GetMaterialLookupCodeQuery()

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BarcodeReceivingApp.Core.Repositories;
using System.Data.Entity;

namespace BarcodeReceivingApp.Persistence.Repositories
{
    public class MaterialRepository : Repository<Material>, IMaterialRepository
    {
        public MaterialRepository(BarcodeReceivingDbContext context)
            : base(context)
        {

        }
        public async Task<IEnumerable<string>> GetMaterialLookupCodeQuery()
        {
            return await BarcodeReceivingDbContext.Materials.Include(m => m.MaterialLookupCode).Select(m => m.MaterialLookupCode);
        }

        public BarcodeReceivingDbContext BarcodeReceivingDbContext
        {
            get { return Context as BarcodeReceivingDbContext; }
        }
    }
}

这是该类的接口

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BarcodeReceivingApp.Core.Repositories
{
    public interface IMaterialRepository : IRepository<Material>
    {
        Task<IEnumerable<string>> GetMaterialLookupCodeQuery();
    }
}
c# winforms linq async-await entity-framework-4
1个回答
0
投票

Linq使用关键字yield return,这表示在调用之前我们不会实际执行操作。所以你的避免代码试图等待懒惰调用方法的操作。

根据这个MSDN

Although it's less code, take care when mixing LINQ with asynchronous code. Because LINQ uses deferred (lazy) execution, async calls won't happen immediately as they do in a foreach() loop unless you force the generated sequence to iterate with a call to .ToList() or .ToArray().

所以,失去了等待。在使用结果之前,您实际上并未执行该语句

© www.soinside.com 2019 - 2024. All rights reserved.