Skip to content

Commit

Permalink
[Foundation] Fix hack in NSUrlSessionHandler to avoid a deadlock. (#2…
Browse files Browse the repository at this point in the history
…0327)

Calling [Try]SetResult on a default TaskCompletionSource will call any
continuations on the same thread.

This can lead to deadlocks (thus the hack to run TrySetResult in a background
thread), so avoid it by configuring the TaskCompletionSource to call
continutations asynchronously.

Ref: https://devblogs.microsoft.com/premier-developer/the-danger-of-taskcompletionsourcet-class/
  • Loading branch information
rolfbjarne authored Mar 19, 2024
1 parent 120d6e3 commit bb775d0
Showing 1 changed file with 2 additions and 3 deletions.
5 changes: 2 additions & 3 deletions src/Foundation/NSUrlSessionHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -987,8 +987,7 @@ void SetResponse (InflightData inflight)

inflight.ResponseSent = true;

// EVIL HACK: having TrySetResult inline was blocking the request from completing
Task.Run (() => inflight.CompletionSource.TrySetResult (httpResponse!));
inflight.CompletionSource.TrySetResult (httpResponse!);
}
}

Expand Down Expand Up @@ -1170,7 +1169,7 @@ class InflightData {
public readonly object Lock = new object ();
public string RequestUrl { get; set; }

public TaskCompletionSource<HttpResponseMessage> CompletionSource { get; } = new TaskCompletionSource<HttpResponseMessage> ();
public TaskCompletionSource<HttpResponseMessage> CompletionSource { get; } = new TaskCompletionSource<HttpResponseMessage> (TaskCreationOptions.RunContinuationsAsynchronously);
public CancellationToken CancellationToken { get; set; }
public CancellationTokenSource CancellationTokenSource { get; } = new CancellationTokenSource ();
public NSUrlSessionDataTaskStream Stream { get; } = new NSUrlSessionDataTaskStream ();
Expand Down

7 comments on commit bb775d0

@vs-mobiletools-engineering-service2

This comment was marked as outdated.

@vs-mobiletools-engineering-service2

This comment was marked as outdated.

@vs-mobiletools-engineering-service2

This comment was marked as outdated.

@vs-mobiletools-engineering-service2

This comment was marked as outdated.

@vs-mobiletools-engineering-service2

This comment was marked as outdated.

@vs-mobiletools-engineering-service2

This comment was marked as outdated.

@vs-mobiletools-engineering-service2
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📚 [CI Build] Artifacts 📚

Packages generated

View packages

Pipeline on Agent
Hash: [CI build]

Please sign in to comment.