-
Notifications
You must be signed in to change notification settings - Fork 0
/
InternetConnectionManagment.cs
79 lines (72 loc) · 2.53 KB
/
InternetConnectionManagment.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Weather_Rider
{
public class InternetConnectionManagment
{
private readonly PictureBox icon;
private bool isConnected = false;
private readonly CancellationTokenSource cts;
private Task blinkingTask;
public InternetConnectionManagment(PictureBox icon)
{
this.icon = icon ?? throw new ArgumentNullException(nameof(icon));
cts = new CancellationTokenSource();
blinkingTask = Task.Run(() => IconBlinkCallback(cts.Token));
}
public void CheckConnection()
{
Debug.WriteLine("Checking connection...");
if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
isConnected = true;
Debug.WriteLine("Connected to the internet.");
}
else
{
isConnected = false;
Debug.WriteLine("Not connected to the internet.");
}
}
private async Task IconBlinkCallback(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
try
{
if (icon.IsHandleCreated && !icon.IsDisposed)
{
icon.Invoke(() =>
{
if (!isConnected)
{
icon.Visible = !icon.Visible;
}
else
{
icon.Visible = false;
}
});
}
await Task.Delay(500, token); // Obsługa anulowania w Task.Delay
}
catch (OperationCanceledException)
{
Debug.WriteLine("Blinking task canceled.");
break;
}
catch (InvalidOperationException) { };
}
}
public void Close()
{
Debug.WriteLine("Closing InternetConnectionManagment...");
cts.Cancel(); // Sygnalizuj zakończenie zadania
blinkingTask.Wait(); // Poczekaj na zakończenie zadania
cts.Dispose(); // Zwolnij zasoby tokena
}
}
}