Skip to content

Commit

Permalink
Fix for threading issue in ResourceNotificationService.
Browse files Browse the repository at this point in the history
  • Loading branch information
mitchdenny committed Sep 11, 2024
1 parent fb8f413 commit 995e875
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

var builder = DistributedApplication.CreateBuilder(args);

var sql1 = builder.AddSqlServer("sql1").AsAzureSqlDatabase();
var sql1 = builder.AddSqlServer("sql1").PublishAsAzureSqlDatabase();
var db1 = sql1.AddDatabase("db1");

var sql2 = builder.AddSqlServer("sql2").PublishAsContainer();
Expand Down
15 changes: 12 additions & 3 deletions src/Aspire.Hosting/ApplicationModel/ResourceNotificationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,8 @@ public async Task<ResourceEvent> WaitForResourceAsync(string resourceName, Func<
throw new OperationCanceledException($"The operation was cancelled before the resource met the predicate condition.");
}

private readonly object _onResourceUpdatedLock = new();

/// <summary>
/// Watch for changes to the state for all resources.
/// </summary>
Expand All @@ -156,7 +158,10 @@ public async IAsyncEnumerable<ResourceEvent> WatchAsync([EnumeratorCancellation]
void WriteToChannel(ResourceEvent resourceEvent) =>
channel.Writer.TryWrite(resourceEvent);

OnResourceUpdated += WriteToChannel;
lock (_onResourceUpdatedLock)
{
OnResourceUpdated += WriteToChannel;
}

try
{
Expand All @@ -167,7 +172,10 @@ void WriteToChannel(ResourceEvent resourceEvent) =>
}
finally
{
OnResourceUpdated -= WriteToChannel;
lock (_onResourceUpdatedLock)
{
OnResourceUpdated -= WriteToChannel;
}

channel.Writer.TryComplete();
}
Expand Down Expand Up @@ -212,10 +220,11 @@ public Task PublishUpdateAsync(IResource resource, string resourceId, Func<Custo
{
_logger.LogTrace("Resource {Resource}/{ResourceId} update published: " +
"ResourceType = {ResourceType}, CreationTimeStamp = {CreationTimeStamp:s}, State = {{ Text = {StateText}, Style = {StateStyle} }}, " +
"HealthStatus = {HealthStatus} " +
"ExitCode = {ExitCode}, EnvironmentVariables = {{ {EnvironmentVariables} }}, Urls = {{ {Urls} }}, " +
"Properties = {{ {Properties} }}",
resource.Name, resourceId,
newState.ResourceType, newState.CreationTimeStamp, newState.State?.Text, newState.State?.Style,
newState.ResourceType, newState.CreationTimeStamp, newState.State?.Text, newState.State?.Style, newState.HealthStatus,
newState.ExitCode, string.Join(", ", newState.EnvironmentVariables.Select(e => $"{e.Name} = {e.Value}")), string.Join(", ", newState.Urls.Select(u => $"{u.Name} = {u.Url}")),
string.Join(", ", newState.Properties.Select(p => $"{p.Name} = {p.Value}")));
}
Expand Down

0 comments on commit 995e875

Please sign in to comment.