I have this solution using reactive extension. I had to increase the timespans by an order, because the sleep is not precise enough. The following code shows that the actual
variable is increasing even when the previous failed.
You have to tweak some on the mymethod()
function also. If the expensive method is an I/O heavy function, than split it up into buffers, and each buffers writing/reading You can check if the token is still not cancelled. This way, the length of the blocking part can be adjusted.
static Random rand = new Random();
static void Main(string[] args) {
var obs = Observable.Interval(TimeSpan.FromMilliseconds(250)).Do<long>(i =>
{
CancellationTokenSource source = new CancellationTokenSource(250);
ReadNext(source.Token, i);
}).Publish();
var disp = obs.Connect();
Console.ReadKey();
disp.Dispose();
Console.ReadKey();
}
static private void ReadNext(CancellationToken token, long actual) {
int i = rand.Next(4);
for(int j = 0; j < i; j++) {
Thread.Sleep(100);
if(token.IsCancellationRequested) {
Console.WriteLine(string.Format("method cancelled. cycles: {0}, should be 3. Now should be last (2): {1}", i, j));
return;
}
}
Console.WriteLine(string.Format("method done in {0} cycles. Preserved index: {1}.", i, actual));
}
example printout:
method done in 2 cycles. Preserved index: 4.
method done in 0 cycles. Preserved index: 5.
method done in 0 cycles. Preserved index: 6.
method done in 2 cycles. Preserved index: 7.
method done in 1 cycles. Preserved index: 8.
method cancelled. cycles: 3, should be 3. Now should be last (2): 2
method done in 0 cycles. Preserved index: 10.
method cancelled. cycles: 3, should be 3. Now should be last (2): 2
method cancelled. cycles: 3, should be 3. Now should be last (2): 2
method cancelled. cycles: 3, should be 3. Now should be last (2): 2
method done in 1 cycles. Preserved index: 14.
method cancelled. cycles: 3, should be 3. Now should be last (2): 2
method done in 1 cycles. Preserved index: 16.
method done in 2 cycles. Preserved index: 17.
method cancelled. cycles: 3, should be 3. Now should be last (2): 2
method done in 2 cycles. Preserved index: 19.
method done in 1 cycles. Preserved index: 20.
method done in 2 cycles. Preserved index: 21.
method done in 2 cycles. Preserved index: 22.
method done in 1 cycles. Preserved index: 23.
method done in 1 cycles. Preserved index: 24.
method done in 1 cycles. Preserved index: 25.
method done in 2 cycles. Preserved index: 26.
method done in 1 cycles. Preserved index: 27.