简体   繁体   中英

Check if Task<bool> is true or false (C#)

I had method, to check count of Landlords шт LandlordTypes

I had this code to check it

var type = _landlordTypeRepository.GetAll()
    .Include(x => x.Landlords)
    .FirstOrDefault(x => x.Id == input.Id);

if (type.Landlords.Count > 0)
{
    throw new UserFriendlyException(L("ThisTypeIsInUse"));
}

But I rewrote it like this

var type = _landlordTypeRepository
    .GetAll()
    .AnyAsync(x=> x.Id == input.Id && x.Landlords.Any());

But now return type id Task<bool>

How I can use this in if?

You need to use await :

var type = await _landlordTypeRepository.GetAll().AnyAsync(x=> x.Id == input.Id && x.Landlords.Any());

You method must also be marked as async .

I recommend you get acquainted with async - await .

Use await to "unwrap" Task result

bool type = await _landlordTypeRepository.GetAll().AnyAsync(x=> x.Id == input.Id && x.Landlords.Any());

Also mark calling method as async

async Task SomeMethod() {
    //..

    bool type = await _landlordTypeRepository.GetAll().AnyAsync(x=> x.Id == input.Id && x.Landlords.Any());

    //..
}

You can either use the await keyword or simply put .Result at the end of a task to get the value you are looking for.

When using await , your method's signature must have async and must also return a Task (eg Task<string> or simply Task for void) unless it's an event which can then be async void .

Using .Result , will block the current thread which means can freeze the UI as well!

A Task is a reference data structure used for asynchronous calls. It contains a .Result-property which will be filled with the return value once the call has completed. Since it is an asynchronous call you cannot know for sure that the call has been completed when receiving a Task the way you have done here.

There is two main ways of dealing with this:

  1. If you're inside an asynchronous context (method using the async keyword), you could just use the await -keyword to wait for and unwrap the result. var type = await _landlordRepository.GetAll().AnyAsync(...);

  2. If you're in a synchronous context, you can use Task.Wait() to await the call and then read the result value from Task<T>.Result .

    var task = _landlordRepository.GetAll().AnyAsync(...).Wait(); var type = task.Result

As people have pointed out, using .Result is usually not advised since it is a blocking call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM