Skip to content

Commit cabd55b

Browse files
committed
Small fixes improving threads synchronization.
1 parent fd88f43 commit cabd55b

File tree

2 files changed

+14
-18
lines changed

2 files changed

+14
-18
lines changed

Logic/LogicAPI.cs

Lines changed: 12 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,14 @@
22
using System;
33
using System.Collections.ObjectModel;
44
using System.Numerics;
5+
using System.Threading;
56

67
namespace 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);

ViewModel/MainWindowViewModel.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,10 +63,10 @@ public int viewWidth
6363
get { return _width; }
6464
}
6565

66-
private void CreateHandler()
66+
private async void CreateHandler()
6767
{
6868
ballsGroup = _modelLayer.createBalls(_ballsAmount, 25);
69-
_modelLayer.StartSimulation();
69+
await Task.Run(() => _modelLayer.StartSimulation());
7070
}
7171

7272
private void StopHandler()

0 commit comments

Comments
 (0)