Put a semaphore in there. Then just set the semaphore from elsewhere. For example, a simple public boolean property that is normally false. In the foreach loop above, if the value of the boolean is false, then the code proceeds as normal. If the boolean is true, it pauses. You might implement this as:
foreach( XElement..... )
{
while( this.Semaphore ) Thread.Sleep(5);
}
Then, where you want to pause, just set the semaphore when you want it paused. For example, if you have an event handler on a button labelled "Pause", when the event fires, check the semaphore. If it's false, then set it to true and change the button text to "Resume". If it's true, then change it to false and set the button text to "Pause". Something like this:
protected void MyButton_ClickEvent( object sender, EventArgs e)
{
myThread.Semaphore = !myThread.Semaphore;
if( myThread.Semaphore ) ( (Button)sender ).Text = "Resume";
else ( (Button)sender ).Text = "Pause";
}
Boom. Problem solved. If you have a whole bunch of threads, then just extend the idea. Maybe have a list of the threads running with checkboxes next to each that set/clear the semaphore for that particular thread so you can pause/resume specific threads at will, or just have one button pause/resume everything. Whatever you need.