First off, apologies for the title; I couldn't really think of how to succinctly articulate what I'm trying to do.
I have the following two functions:
Main code:
private async Task<PreparationInfo> PrepareRoundtrip()
{
PreparationInfo output = new PreparationInfo();
Task.Delay(3000); // stands in for a call to the server to fetch data for how to prepare
prepare(output) // package result into output
return output;
}
private Task ExecuteWithPrepare()
{
if (!PrepareEnabled) // instance variable
return stateObject.Execute();
else
{
Task<PreparationInfo> prepareTask = PrepareRoundtrip();
return tceTask.ContinueWith((prepareTaskInternal) =>
{
stateObject.Execute(); // this is the Task that I need to return
});
}
}
stateObject.Execute() header:
internal Task Execute()
{
...
}
I'm writing a wrapper for the stateObject.Execute()
method that will optionally call a preparation method (PrepareRoundtrip()
) beforehand to process some parameters before executing.
If preparation is not enabled (PrepareEnabled == false
), I can just call Execute()
direction and immediately return the Task it returns. If preparation is enabled, I need to run the preparation method (which is unique to this task, I can change it however necessary), then run Execute()
.
The part I'm stuck on is this:
The entire function needs to run and return as though stateObject.Execute()
was called directly, just with the PrepareRoundtrip()
part added, meaning two things:
The Task that gets returned from
ExecuteWithPrepare()
needs to represent the Task thatstateObject.Execute()
returns.ExecuteWithPrepare()
needs to return immediately (i.e. not wait for the 3 second delay inPrepareRoundtrip()
What's the best way to achieve this? Thanks!
TL;DR:
Adding a wrapper for stateObject.Execute()
to add an extra preparation step that's potentially lengthy; need the whole thing to return a Task representing the original result immediately rather than waiting for the preparation step to complete first.