views:

25

answers:

1

Lets assume I have such code for testing.

public class SimpleScheduler
{
    public Script Script { get; set; }

    private Thread _worker;

    public void Schedule()
    {
        this._worker = new Thread(this.Script.Execute);
        this._worker.Start();
    }

    public void Sleep()
    {
        //?
    }
}

SimpleScheduler just takes Script object and tries to execute it in separate thread.

    public class Script
    {
        public string ID { get; set; }

        private ScriptSource _scriptSource;

        private ScriptScope _scope;

        private CompiledCode _code;

        private string source = @"import clr
clr.AddReference('Trampoline')
from Trampoline import PythonCallBack
def Start():
   PythonCallBack.Sleep()";

        public Script()
        {
            _scriptSource = IronPythonHelper.IronPythonEngine.CreateScriptSourceFromString(this.source);
            _scope = IronPythonHelper.IronPythonEngine.CreateScope();
            _code = _scriptSource.Compile();
        }

        public void Execute()
        {
            _code.Execute(_scope);
            dynamic start = _scope.GetVariable("Start");
            start();
        }
    }

Script class tries to callback Sleep function of PythonCallBack class and wants to be suspended for some time.

public static class PythonCallBack
{
    public static SimpleScheduler Scheduler;

    static PythonCallBack()
    {
        Scheduler = new SimpleScheduler();
    }

    public static void Sleep()
    {
        Scheduler.Sleep();
    }
}

PythonCallBack just for calling sleep method of SimpleScheduler.

Question: What is the best way to suspend thread, which executes Script? and then how to resume this thread execution?

+1  A: 

The Thread class has a Suspend() and Resume() method. These methods suspend and resume the thread. Even though there is a warning concerning this method, this should not be a problem because you are suspending at a known location.

An alternative is to use events. You can give the Script or ScriptScope class a AutoResetEvent. Then, in the Sleep(), you call WaitOne() on the event. Then, from the outside, when you want the thread to resume, you call Set().

Pieter
Suspend() and Resume() methods are deprecated and unsafe for threads synchronization
Jevgenij Nekrasov
Updated the answer.
Pieter