Check if this works:
public Task<bool> IsFileNameExists(string fileName)
{
return Task.Run( () => Database.Table<DataEntriesModel>().Where(x => x.FileName == fileName).FirstOrDefault() != null);
}
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I never went beyond returning Task.FromResult(computedValue)
in my asynchronous programming.
I was wondering if it is possible to return a Task even when computedValue
is yet to be determined from another pending Task as illustrated below.
THE EASY ONE:
public Task<bool> IsFileNameExists(string fileName)
{
bool isFileExists = CheckIfFileNameExists(fileName);
return Task.FromResult(isFileExits );
}
THE NOT EASY:
public Task<bool> IsFileNameExists(string fileName)
{
var objectResult = Database.Table<DataEntriesModel>().Where(x => x.FileName == fileName).FirstOrDefault(); // this is returning Task
// What I want to return is CompletedTask result is not null.
// I cannot use the following because objectResult is a pending, and pending Task is not null even if completed task is null
// and objectResult != null will always be true.
return Task.FromResult(objectResult != null);
}
Yes, I can make the method async Task<bool>
and return an awaited result.
I just wondered if Task<bool>
can still be returned when the <bool>
evaluation is dependent on a pending Task
.
Can this be done and how?
Check if this works:
public Task<bool> IsFileNameExists(string fileName)
{
return Task.Run( () => Database.Table<DataEntriesModel>().Where(x => x.FileName == fileName).FirstOrDefault() != null);
}
I think that the bool value corresponds to the result of '...FirstOrDefault() != null'. Maybe it was not used correctly after the call.
Hi @Viorel ,
I have tested thoroughly comparing with the alternative with an async method.
What you suggested will always be true because the pending Task to the left of != will always be nonnull, hence the boolean evaluation always true.
I thought I could return Task<bool> and await in the caller, but my only solution now is just await in the called method and return bool value.
I think that it is non-null when Where found the item. It cannot be non-null when Where did not find it.
Use QueryableExtensions.FirstOrDefaultAsync(). Then IsFileNameExists() can be an async method and yield control to the caller.
Viorel-1's sample creates a background thread that is awaitable. Can you share your test code? Keep in mind, for web applications you want to use an async method which is a better use of resources.
The following reference doc explains the mechanics of the async/await pattern.
Task asynchronous programming model
Sign in to comment