I've coded a simplified version of my problem below. So I've got this service and in the method DoSomething
- I want to do a synchronous check ( IsTrue()
method ) followed by an async
call ( database lookup ).
I only want to do the database lookup (EF6 async select - simulated by this.SuperSlowThing
) if the syncResult
is false. This can be done by using &&
which will only continue to asyncResult
in case syncResult
is true.
My question: is this a good solution for this problem? If so, is there an easier way to do this?
internal class MyService
{
public void DoSomething(bool someValue)
{
var syncResult = this.IsTrue(someValue);
var asyncResult = new Lazy<Task<string>>(this.SuperSlowThing);
if (syncResult && asyncResult.Value.Result.Length > 0)
{
Console.WriteLine("Did SuperSlowThing - result is " + asyncResult.Value.Result);
}
else
{
Console.WriteLine("Didn't do SuperSlowThing");
}
}
private bool IsTrue(bool someValue)
{
return someValue;
}
private Task<string> SuperSlowThing()
{
var sw = System.Diagnostics.Stopwatch.StartNew();
while (sw.ElapsedMilliseconds < 5000)
{
Thread.Sleep(500);
Console.WriteLine("Delaying");
}
return Task.FromResult("Done!");
}
}
EDIT
So let me elaborate a bit on what the code does in real life. The DoSomething
method is really a database lookup. If the someValue
is some number that is present in the web.config - then do a database lookup of the number in table A. This is the synchronous operation.
If a result is then found in table A, return that, otherwise lookup the number in table B.
If the number of someValue
was not found in web.config - do the lookup in table B immediately.