开发者

C# - Program execution flow yield/pause/resume

开发者 https://www.devze.com 2023-04-02 02:17 出处:网络
Could you tell me please if there is a way in C# to pause and resume th开发者_运维百科e program execution flow as I would like to do below?

Could you tell me please if there is a way in C# to pause and resume th开发者_运维百科e program execution flow as I would like to do below?

Or do you have an idea how to save/load the current thread call stack?

I am looking for a solution that does not creates new thread at all.

public class MyClass : InterruptableClass
{
    int x;

    public void Fn1()
    {
        x = 1;
        this.Interrupt();
        x = 2;
    }
}

static class Program
{
    static void Main()
    {
        MyClass c = new MyClass();

        c.Fn1();
        // Now c.x is 1

        if (c.IsInterrupted)
        {
            c.ResumeExecution();
            // Now c.x is 2
        }
    }
}

Unfortunately I cannot save / reload the call stack (StackTrace/StackFrame).


You should look into threads and thread synchronization using Events or Locks, depending on which is appropriate for your scenario.

You can tell a thread to wait for other threads or to wait until some event happens using these mechanisms, so that while it is actually waiting it will most likely (depending on OS) be context switched out, so other threads having work to do, can actually get on with work.


You may want to take a look at await keyword that will be introduced in the next version of C#.

If you need the solution now, consider using TPL continuations (Task.ContinueWith method).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号