22using System ;
33using System . Collections . ObjectModel ;
44using System . Numerics ;
5+ using System . Threading ;
56
67namespace Logic
78{
89 public class LogicAPI : LogicAbstractAPI
910 {
1011 private readonly DataAPI _dataAPI ;
11- private CancellationToken _cancellationToken ;
12+ private CancellationTokenSource _cancellationTokenSource ;
1213 private List < Task > _tasks = new List < Task > ( ) ;
1314
1415 public override Table table { get ; }
@@ -23,44 +24,39 @@ public LogicAPI()
2324
2425 public override void RunSimulation ( )
2526 {
26- _cancellationToken = CancellationToken . None ;
27+ _cancellationTokenSource = new CancellationTokenSource ( ) ;
2728 float timeTravel = 0.01f ;
2829
2930 foreach ( BallLogic ball in balls )
3031 {
31- Task task = Task . Run ( ( ) =>
32+ Task task = Task . Run ( async ( ) =>
3233 {
3334 while ( true )
3435 {
35- // Thread.Sleep(TimeSpan.FromSeconds(timeTravel));
36- try
37- {
38- _cancellationToken . ThrowIfCancellationRequested ( ) ;
39- }
40- catch ( OperationCanceledException )
41- {
36+ await Task . Delay ( TimeSpan . FromSeconds ( timeTravel ) , _cancellationTokenSource . Token ) ;
37+ if ( _cancellationTokenSource . Token . IsCancellationRequested )
4238 break ;
43- }
4439 ball . setPosition ( ) ;
4540 }
46- } ) ;
41+ } , _cancellationTokenSource . Token ) ;
4742 _tasks . Add ( task ) ;
4843 }
4944 }
5045
5146 public override void StopSimulation ( )
5247 {
53- _cancellationToken = new CancellationToken ( true ) ;
48+ _cancellationTokenSource ? . Cancel ( ) ;
5449
55- foreach ( Task task in _tasks )
50+ try
5651 {
57- task . Wait ( ) ;
52+ Task . WhenAll ( _tasks ) . Wait ( ) ;
5853 }
54+ catch ( AggregateException ) { }
5955
6056 _tasks . Clear ( ) ;
6157 balls . Clear ( ) ;
6258 }
63-
59+
6460 public override BallLogic createBall ( int radius , Vector2 position )
6561 {
6662 Vector2 basicVelocity = new Vector2 ( ( float ) 0.01 , ( float ) 0.01 ) ;
0 commit comments