I have two methods. I want to wait the first one and some times wait the other (but not all the time). So I think I should use a task and await it when I want to wait, and not await it when I don't want to wait.
EDIT : in fact, I only need a fire and forget call ? :
public class TestController : ApiController
{
public IHttpActionResult Get(int id)
{
Stopwatch sw = Stopwatch.StartNew();
JobRunner runner = new JobRunner();
bool iWantToWait = id == 1;
string jobId = runner.Run(!iWantToWait);
sw.Stop();
return Ok("Ok " + jobId + " # " + sw.Elapsed );
}
}
public class JobRunner
{
public string Run(bool fireAndForget)
{
ShortMethodIAlwaysWantToWait();
string jobId = Guid.NewGuid().ToString("N");
if (fireAndForget)
HostingEnvironment.QueueBackgroundWorkItem(token => LongMethodICouldWantToWaitOrNot(jobId));
else
LongMethodICouldWantToWaitOrNot(jobId);
return jobId;
}
private void ShortMethodIAlwaysWantToWait()
{
// ...
}
private void LongMethodICouldWantToWaitOrNot(string jobId)
{
// ...
}
}