基于TPL的协同多任务处理

2024-04-30 03:08:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我们正在移植建模应用程序,它在建模过程中使用IronPython脚本进行自定义操作。现有的应用程序在单独的线程中执行每个Python脚本,并为此使用协作模型。现在我们想把它移植到TPL,但首先我们要测量上下文切换 . 基本上,我们现在拥有的是:

  1. Tasks队列
  2. 此队列中的每个Task都执行一个IronPython脚本
  3. 在IronPython脚本中,我们调用C#class方法,它是同步点,应该将Task(IronPython执行)转移到等待状态

我们要做的是:

  1. 我们想要做一个无限循环,它将遍历Task的队列
  2. 当我们得到一个Task时,我们尝试执行它
  3. 在PythonScript中,我们希望调用C#方法并将此脚本转移到等待状态。但不能从队列中删除它。在
  4. 在下一次迭代中,当我们得到另一个Task时,我们检查它是否处于等待状态。如果是这样的话,我们就把它叫醒,然后试着去执行。在
  5. 在每一刻我们应该只有一个活跃的Task
  6. 最后,我们要测量每秒可以执行多少Task

我真的不知道这是合作多任务处理吗? 我们正在考虑定制TaskScheduler,这是个好方法吗?或者有人知道更好的解决方案吗?在

谢谢。在

更新时间:

好的,例如,我有这样的代码:

public class CooperativeScheduler : TaskScheduler, IDisposable
    {
        private BlockingCollection<Task> _tasks;

        private Thread _thread;

        private Task _currentTask;

        public CooperativeScheduler()
        {
            this._tasks = new BlockingCollection<Task>();
            this._thread = new Thread(() =>
                {
                    foreach (Task task in this._tasks.GetConsumingEnumerable())
                    {
                        this._currentTask = task;

                        TryExecuteTask(this._currentTask);
                    }
                }
            );

            this._thread.Name = "Cooperative scheduler thread";

            this._thread.Start();
        }

        public void SleepCurrentTask()
        {
            if (this._currentTask != null)
            {
                // what to do here?
            }
        }

        protected override IEnumerable<Task> GetScheduledTasks()
        {
            return this._tasks.ToArray<Task>();
        }

        protected override void QueueTask(Task task)
        {
            // No long task
            this._tasks.Add(task);
        }

        protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
        {
            throw new NotImplementedException();
        }

        public void Dispose()
        {
            this._tasks.CompleteAdding();
            this._thread.Join();
        }
   }

自定义任务调度器,它有一个用于任务执行的_thread和用于运行任务的_currentTask字段,而且它还有{}在这个方法中我想暂停当前任务的执行,但我不知道如何。在

客户端代码很简单:

^{pr2}$

也许有人有更好的主意?在


Tags: 方法脚本newtask队列状态privatepublic