Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Guard against work being queued on an already-disposed ThreadedTaskScheduler #5320

Merged
merged 5 commits into from
Aug 2, 2022
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
20 changes: 20 additions & 0 deletions osu.Framework.Tests/Threading/ThreadedTaskSchedulerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,5 +65,25 @@ public void EnsureEventualDisposalWithStuckTasks()

Assert.That(exited.Wait(30000));
}

[Test]
public void EnsureScheduledTaskReturnsOnDisposal()
{
ManualResetEventSlim exited = new ManualResetEventSlim();
ManualResetEventSlim run = new ManualResetEventSlim();
ThreadedTaskScheduler taskScheduler = new ThreadedTaskScheduler(4, "test");

taskScheduler.Dispose();

Task.Run(async () =>
{
// ReSharper disable once AccessToDisposedClosure
await Task.Factory.StartNew(() => { run.Set(); }, default, TaskCreationOptions.HideScheduler, taskScheduler).ConfigureAwait(false);
exited.Set();
});

Assert.That(run.Wait(30000));
Assert.That(exited.Wait(30000));
}
}
}
15 changes: 14 additions & 1 deletion osu.Framework/Threading/ThreadedTaskScheduler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using osu.Framework.Logging;

namespace osu.Framework.Threading
{
Expand Down Expand Up @@ -82,7 +83,19 @@ private void processTasks()
/// Queues a Task to be executed by this scheduler.
/// </summary>
/// <param name="task">The task to be executed.</param>
protected override void QueueTask(Task task) => tasks.Add(task);
protected override void QueueTask(Task task)
{
try
{
tasks.Add(task);
}
catch (ObjectDisposedException)
{
// tasks may have been disposed. there's no easy way to check on this other than catch for it.
Logger.Log($"Task was queued for execution on a {nameof(ThreadedTaskScheduler)} ({name}) after it was disposed. The task will be executed inline.");
TryExecuteTask(task);
}
}

/// <summary>
/// Provides a list of the scheduled tasks for the debugger to consume.
Expand Down