Skip to content

Instantly share code, notes, and snippets.

@RickyLin
Created March 18, 2022 14:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RickyLin/7b18937dd7e7f389fe89cc91445a2932 to your computer and use it in GitHub Desktop.
Save RickyLin/7b18937dd7e7f389fe89cc91445a2932 to your computer and use it in GitHub Desktop.
CurrentThreadTaskScheduler
/* The CurrentThreadTaskScheduler code comes from
* https://github.com/dotnet/samples/blob/main/csharp/parallel/ParallelExtensionsExtras/TaskSchedulers/CurrentThreadTaskScheduler.cs
*/
/// <summary>
/// Provides a task scheduler that runs tasks on the current thread.
/// </summary>
public sealed class CurrentThreadTaskScheduler : TaskScheduler
{
/// <summary>Runs the provided Task synchronously on the current thread.</summary>
/// <param name="task">The task to be executed.</param>
protected override void QueueTask(Task task) => TryExecuteTask(task);
/// <summary>Runs the provided Task synchronously on the current thread.</summary>
/// <param name="task">The task to be executed.</param>
/// <param name="taskWasPreviouslyQueued">Whether the Task was previously queued to the scheduler.</param>
/// <returns>True if the Task was successfully executed; otherwise, false.</returns>
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) => TryExecuteTask(task);
/// <summary>Gets the Tasks currently scheduled to this scheduler.</summary>
/// <returns>An empty enumerable, as Tasks are never queued, only executed.</returns>
protected override IEnumerable<Task> GetScheduledTasks() => Enumerable.Empty<Task>();
/// <summary>Gets the maximum degree of parallelism for this scheduler.</summary>
public override int MaximumConcurrencyLevel => 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment