美好的一天。我需要執行一些任務func異步。但如何做到這一點?C#:LINQ中的異步
public async Task<string> GetPersonForSchedule(int[] usedStaff, string position)
{
var result = await staffRepository
.GetMany()
.Where(async elem => await IsGoodPersonForSchedule(elem, usedStaff, position))
.ToListAsync();
return await Task.Factory.StartNew(() => JsonConvert.SerializeObject(result));
}
private async Task<bool> IsGoodPersonForSchedule(Person person, int[] usedStaff, string position)
{
//...
var currPersonFlights = await flightStaffRepository
.GetMany()
.Include(elem => elem.Flight)
.Where(elem => IsDateSuitable(elem.Flight.FlightDate.Value))
.Include(elem => elem.Flight.Route)
.ToListAsync();
//...
return true;
}
因此,在該行.Where(async elem => await IsGoodPersonForSchedule(elem, usedStaff, position))
我有一個錯誤:
Cannot convert async lambda expression to delegate type
Func<Person, bool>
. An async lambda expression may return void, Task or Task, none of which are convertible toFunc<Person, bool>
.
,我發現這是解決方案: .Where(elem => IsGoodPersonForSchedule(elem, usedStaff, position).Result)
但它就是這麼奇怪,異步方法的使用結果屬性...它編譯沒有錯誤。也許你知道另一種解決方案
有關序列化到JSON創建線程:是的,我同意你的觀點,創造新的線程應該花更多的時間比在當前線程執行此。感謝您對linq中的異步解釋。 – Evgeniy175