Skip to content

Instantly share code, notes, and snippets.

@StephenCleary
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StephenCleary/41667b966731e94ad49d to your computer and use it in GitHub Desktop.
Save StephenCleary/41667b966731e94ad49d to your computer and use it in GitHub Desktop.
// I'm starting 10 calls at every 50 msec. Each call has a random execution time between 1-19 seconds.
// Many times the last answer comes from the 9th call instead of the 10th.
// I'm not sure I'm testing it properly.
void Main()
{
var rand = new Random();
Enumerable.Range(1,10)
.Select(async (e) => {
Thread.Sleep(50);
return await StartBacktestAsync(id: e, length: rand.Next(1,20));
})
.ToList()
.ForEach(async (r) => {
var id = await r;
if (id > 0)
Console.WriteLine("Completed {0}", id);
});
}
private CancellationTokenSource _cts;
private async Task<int> StartBacktestAsync(int id, int length)
{
if (_cts != null)
_cts.Cancel();
_cts = new CancellationTokenSource();
Console.WriteLine("Started {0}", id);
try
{
var token = _cts.Token;
return await Task.Run(() => Backtest(token, id, length)).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
Console.WriteLine("Canceled {0}", id);
return -1;
}
}
private int Backtest(CancellationToken token, int id, int length)
{
for (int i = 0; i < length; i++)
{
token.ThrowIfCancellationRequested();
Thread.Sleep(1000);
}
token.ThrowIfCancellationRequested();
return id;
}
///
// Results
Started 1
Started 2
Started 3
Started 4
Started 5
Started 6
Started 7
Started 8
Started 9
Started 10
Canceled 1
Canceled 2
Canceled 3
Canceled 4
Canceled 5
Canceled 6
Canceled 7
Canceled 8
Completed 10
Completed 9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment