Hi,

I'm compiling C# code to memory and running it from there, now what I want to do is pause, resume, stop that same code running in the memory.

I'm using this currently to run the code:

private void compileRunToolStripMenuItem_Click(object sender, EventArgs e)
{
    Thread runCode = new Thread(new ThreadStart(RunTheCode));
    runCode.Start();
}

I tried doing runCode.Suspend(); but it doesn't work, and it says its deprecated... Please help, Thanks!!!!

Recommended Answers

All 6 Replies

The Suspend method has been deprecated because it is unsafe, since you are never certain where you stopped the threads execution. Instead you could declared a boolean variable, and then check it at certain points during the execution of the thread. For example:

public void RunTheCode()
{
	while(true)
	{
		//some code
		while(pause) ;
	}
}

Then you need to set the pause variable when you want to pause the current thread, and it will pause after the current iteration of the while loop has finished.

The thing is that, the code is translated into assemble and executed from the memory...

Is it possible to like interrupt the thread and do like Thread.Sleep(1) in a loop...? If so, how? :)

Thanks!

Good point @nmaillet. Use boolean (volatile) instance variable to control a thread.

public class Best
{
    volatile bool flag=true ;
    Thread thread;
    public Best()
    {
        thread=new Thread(new ThreadStart(Run));
        thread.Start();
    }
    public void Stop()
    {
        flag = false;
    }
    public void Run()
    {
        
        while (flag)
        {
            Console.WriteLine("{0}", DateTime.Now.ToShortTimeString());
        }
    }
}
Best a = new Best();
  Thread.Sleep(1000); 
  a.Stop(); // Stop this thread after approximate 1000 millsec.
commented: I didn't know about volatile. I always lock()'d. Good post! +6

It's hard to determine exactly what/how you are trying to achieve this. If you have a handle to the thread, you could have it Sleep() in a loop until you are ready for it to resume processing:

bool suspend = true;//  set to false to continue processing
void SuspendRun ()
{
    suspend = true;
    while (suspend)
        thread.Sleep(1000);
}
void ContinueRun()
{
    suspend = false; // will cause loop above to break and continue processing
}

I will suggest declare a variable that controls your thread, when this variable has certain value you can send the thread to sleep for x seconds, and then wake it up again. What I mean with this is use like semaphores in C++

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.