Add Semaphore

This commit is contained in:
Li 2023-11-05 19:28:08 +13:00
parent 0f9f0c8d9c
commit 54e7ae097f
2 changed files with 16 additions and 5 deletions

View File

@ -4,7 +4,7 @@ https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project>
<PropertyGroup>
<History>True|2023-10-18T01:13:41.8203499Z;True|2023-10-18T14:05:36.8381808+13:00;True|2023-10-17T21:30:38.9682339+13:00;</History>
<History>True|2023-11-05T06:18:40.8205304Z;True|2023-11-05T19:17:01.7660736+13:00;True|2023-11-05T19:11:32.6382930+13:00;True|2023-11-05T19:11:09.6820258+13:00;False|2023-11-05T19:10:42.2427675+13:00;True|2023-10-18T14:13:41.8203499+13:00;True|2023-10-18T14:05:36.8381808+13:00;True|2023-10-17T21:30:38.9682339+13:00;</History>
<LastFailureDetails />
</PropertyGroup>
</Project>

View File

@ -7,6 +7,7 @@ using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace PluralRichPresence.SimplyPlural
{
@ -15,9 +16,9 @@ namespace PluralRichPresence.SimplyPlural
public const int KEEPALIVE_INTERVAL = 10 * 1000;
public const string WEBSOCKET_SERVER_URI = "wss://api.apparyllis.com/v1/socket";
public event EventHandler FronterChanged;
SemaphoreSlim semaphore = new SemaphoreSlim(1, 1);
ClientWebSocket? wss = null;
Timer? keepAliveTimer = null;
private void onFronterChanged(dynamic fronterChangedEventData)
{
@ -90,7 +91,8 @@ namespace PluralRichPresence.SimplyPlural
}
private async Task reconnect()
{
if (!await semaphore.WaitAsync(0)) return;
while (true)
{
try
@ -110,7 +112,12 @@ namespace PluralRichPresence.SimplyPlural
catch (Exception) { Console.WriteLine("failed to connect."); continue; }
break;
}
try
{
semaphore.Release();
}
catch (SemaphoreFullException) { };
}
private async Task connect()
@ -123,7 +130,11 @@ namespace PluralRichPresence.SimplyPlural
private async Task sendText(string text)
{
Console.WriteLine("> "+text);
await wss.SendAsync(Encoding.UTF8.GetBytes(text), WebSocketMessageType.Text, true, CancellationToken.None);
try
{
await wss.SendAsync(Encoding.UTF8.GetBytes(text), WebSocketMessageType.Text, true, CancellationToken.None);
}
catch (Exception) { await reconnect(); }
}
private async Task sendKeepAlive()
{