Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using FeatBit.Sdk.Server.Options;
using FeatBit.Sdk.Server.Store;
using FeatBit.Sdk.Server.Transport;
using FeatBit.Sdk.Server.Utils;
using Microsoft.Extensions.Logging;

namespace FeatBit.Sdk.Server.DataSynchronizer
Expand Down Expand Up @@ -66,7 +67,7 @@ private static FbWebSocket DefaultFbWebSocketFactory(FbOptions options)

public Task<bool> StartAsync()
{
Task.Run(() => _webSocket.ConnectAsync());
_webSocket.ConnectAsync().Forget();

return _initTcs.Task;
}
Expand Down
10 changes: 9 additions & 1 deletion src/FeatBit.ServerSdk/Transport/FbWebSocket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,15 @@ private void CompleteClose(Exception exception = null, string message = "")

private async Task KeepAliveAsync(CancellationToken ct = default)
{
await SendAsync(PingMessage, ct);
try
{
await SendAsync(PingMessage, ct);
}
catch (InvalidOperationException)
{
// the pipe write will throw InvalidOperationException if the connection is closed
Comment thread
deleteLater marked this conversation as resolved.
// catch and ignore it to avoid UnobservedTaskException
}

Log.InvokingEventHandler(_logger, nameof(OnKeepAlive));
_ = OnKeepAlive?.Invoke();
Expand Down
37 changes: 37 additions & 0 deletions src/FeatBit.ServerSdk/Utils/TaskExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System.Threading.Tasks;

namespace FeatBit.Sdk.Server.Utils;

public static class TaskExtensions
{
/// <summary>
/// Observes the task to avoid the UnobservedTaskException event to be raised.
/// </summary>
public static void Forget(this Task task)
{
if (!task.IsCompleted || task.IsFaulted)
{
_ = ForgetAwaited(task);
Comment thread
deleteLater marked this conversation as resolved.
}

return;

static async Task ForgetAwaited(Task task)
{
#if NET8_0_OR_GREATER
await task.ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing);
#else

try
{
// No need to resume on the original SynchronizationContext, so use ConfigureAwait(false)
await task.ConfigureAwait(false);
}
catch
{
// Nothing to do here
}
#endif
}
}
}
Loading