在C#中,您可以使用TaskScheduler
類來創建和管理任務。要配置TaskScheduler
,您需要創建一個繼承自TaskScheduler
的自定義類,并重寫Initialize
和Run
方法。以下是一個簡單的示例,展示了如何創建一個自定義的TaskScheduler
:
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
public class CustomTaskScheduler : TaskScheduler
{
private readonly ConcurrentQueue<Task> _tasks = new ConcurrentQueue<Task>();
private readonly ManualResetEvent _taskReadyEvent = new ManualResetEvent(false);
private readonly object _lock = new object();
protected override IEnumerable<Task> GetScheduledTasks()
{
lock (_lock)
{
return _tasks;
}
}
public void EnqueueTask(Task task)
{
if (task == null)
{
throw new ArgumentNullException("task");
}
lock (_lock)
{
_tasks.Enqueue(task);
_taskReadyEvent.Set();
}
}
protected override void Run()
{
while (true)
{
Task task = null;
bool success = false;
lock (_lock)
{
if (!_tasks.IsEmpty)
{
task = _tasks.Dequeue();
success = true;
}
}
if (!success)
{
_taskReadyEvent.WaitOne(1000);
}
else
{
try
{
base.Run();
}
catch (Exception ex)
{
Console.WriteLine("An error occurred while running the task: " + ex.Message);
}
}
}
}
}
要使用此自定義TaskScheduler
,您需要創建一個實例并將其傳遞給Task.Run
方法。例如:
public class Program
{
public static void Main(string[] args)
{
CustomTaskScheduler customScheduler = new CustomTaskScheduler();
Task task = Task.Run(() =>
{
Console.WriteLine("Task is running on thread: " + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(1000);
Console.WriteLine("Task completed.");
}, CancellationToken.None, TaskCreationOptions.None, customScheduler);
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
在這個示例中,我們創建了一個CustomTaskScheduler
實例,并將其傳遞給Task.Run
方法。這將確保任務在自定義調度器上運行。