簡體   English   中英

C#中的linq查詢返回異步任務方法問​​題

[英]Async task method issue on a linq query return in c#

我在異步任務方面需要幫助,我試圖返回來自數據庫的值列表,並且我有一個表存儲庫,然后使用該類的存儲庫,我遇到的問題是在方法中使用我的異步任務返回值列表。

這是我的代碼,這里的問題是如何正確使用異步任務,然后在方法中為我的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();
    }
}

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().

因此,無需等待。 在使用結果之前,您實際上並沒有執行該語句

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM