I am trying to do fiber-like code that I can get into task and get out of it. The code I tried:
class TaskActivity {
CancellationTokenSource _m=new CancellationTokenSource( int.MaxValue )
,_t=new CancellationTokenSource( int.MaxValue );
public async Task PauseTask( ) { //call and await it when I want to pause task inside itself
_m.Cancel( );
_t = new CancellationTokenSource( int.MaxValue );
while( !_t.IsCancellationRequested )
await Task.Yield( );
}
public async Task ResumeTask( ) { //call and wait for it when I want to resume a task from the main context
_t.Cancel( );
_m = new CancellationTokenSource( int.MaxValue );
while( !_m.IsCancellationRequested )
await Task.Yield( );
}
}
It works well, but it consumes a lot of CPU when I call Thread.Sleep
at the Task\Main context because it runs in the loop without stop at the other side. When I tried await Task.Delay( int.MaxValue, (_m\_t) );
instead of await Task.Yield( );
, it didn't consumed a lot of CPU but instead it deadlocked sometimes because the Task
doesn't yield to another Task
.
My question is, how to fuse Task.Delay
and Task.Yield
so it doesn't consume a lot of CPU but still able let other Tasks work?