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);
}
You can do the waiting in the caller if you really want to but I don't know that I'd recommend that approach. But honestly your method isn't doing anything that needs additional work so there shouldn't be any awaiting needed at all.
public async Task<bool> IsFileNameExists(string fileName)
{
var objectResult = await Database.Table<DataEntriesModel>().Where(x => x.FileName == fileName).FirstOrDefault(); // this is returning Task
return objectResult != null;
}
But if you wanted to do this in the caller then you'd do something like this.
bool result = Database.Table<...>.Where().FirstOrDefault()
.ContinueWith(x => x != null);
But the problem I'm having is that neither Where
nor FirstOrDefault
are async. Therefore I don't see where in this line of code you are actually using async logic. If Table<>
where to return an async object then the Where
call would be invalid. Hence your first line of code is actually just synchronous.