Simulating the Task mechanism in .net: exploring the mysteries of asynchronous programming

Simulate the Task mechanism in .net: Exploring the mysteries of asynchronous programming Using Task in .net makes it easy to write asynchronous programs. In order to better understand Task and its scheduling mechanism, let’s simulate the implementation of Task in order to understand: What is Task How Tasks are scheduled Basic Task simulation implementation Start with the most basic Task usage Task.Run(Action action) The function of this command is to submit the action as a task to the scheduler, and the scheduler will arrange idle threads to process it. We use Job to simulate Task public class Job { private readonly Action _work; public Job(Action work) => _work = work; public JobStatus Status { get; internal set; } internal protected virtual void Invoke() { Status = JobStatus.Running; _work(); Status = JobStatus.Completed; } public void Start(JobScheduler? scheduler = null) => (scheduler ?? JobScheduler.Current).QueueJob(this); public static Job Run(Action work) { var job = new Job(work); job.Start(); return job; } } public enum JobStatus { Created, Scheduled, Running, Completed } The same static Run method as Task is also defined here, and its usage is similar to Task Job.Run(() => Console.WriteLine($”Job1, thread:{Thread.CurrentThread.ManagedThreadId}”)); For comparison, the writing method when using Task is as follows,…

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索