Skip to content

Commit

Permalink
Merge pull request #484 from Cysharp/hadashiA/fix-async-enumerable
Browse files Browse the repository at this point in the history
Fix problem with finally in UniTaskAsyncEnumerable.Create not being executed
  • Loading branch information
hadashiA authored Aug 31, 2023
2 parents d210e3d + b448680 commit 4c3d693
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
24 changes: 24 additions & 0 deletions src/UniTask.NetCoreTests/Linq/CreateTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,30 @@ public async Task ASyncManually()
list.Should().Equal(100, 200, 300, 400);
}

[Fact]
public async Task AwaitForeachBreak()
{
var finallyCalled = false;
var enumerable = UniTaskAsyncEnumerable.Create<int>(async (writer, _) =>
{
try
{
await writer.YieldAsync(1);
}
finally
{
finallyCalled = true;
}
});

await foreach (var x in enumerable)
{
x.Should().Be(1);
break;
}
finallyCalled.Should().BeTrue();
}

async IAsyncEnumerable<int> Range(int from, int count)
{
for (int i = 0; i < count; i++)
Expand Down
12 changes: 11 additions & 1 deletion src/UniTask/Assets/Plugins/UniTask/Runtime/Linq/Create.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ public _Create(Func<IAsyncWriter<T>, CancellationToken, UniTask> create, Cancell
public UniTask DisposeAsync()
{
TaskTracker.RemoveTracking(this);
writer.Dispose();
return default;
}

Expand Down Expand Up @@ -127,7 +128,7 @@ public void SetResult(T value)
}
}

sealed class AsyncWriter : IUniTaskSource, IAsyncWriter<T>
sealed class AsyncWriter : IUniTaskSource, IAsyncWriter<T>, IDisposable
{
readonly _Create enumerator;

Expand All @@ -137,6 +138,15 @@ public AsyncWriter(_Create enumerator)
{
this.enumerator = enumerator;
}

public void Dispose()
{
var status = core.GetStatus(core.Version);
if (status == UniTaskStatus.Pending)
{
core.TrySetCanceled();
}
}

public void GetResult(short token)
{
Expand Down

0 comments on commit 4c3d693

Please sign in to comment.