Saturday, February 28, 2015
Cancelling ParallelFor
using System.Windows.Forms;
using System.Threading; //Added for thread
namespace Cancelling_ParallelFor
{
public partial class Form1 : Form
{
SynchronizationContext context;
CancellationTokenSource cts = null;
public Form1()
{
InitializeComponent();
}
//To add a way to cancel a Parallel.For method, use the following overload
/*public static ParallelLoopResult For(
int fromInclusive,
int toExclusive,
ParallelOptions parallelOptions,
Action<int> body)
*/
private void btnStartParallelFor_Click(object sender, EventArgs e)
{
//Create a cancellationtokensource
cts = new CancellationTokenSource();
//create a ParallelOptions
ParallelOptions options = new ParallelOptions();
//The ParallelOptions defines a CancellationToken property
//This property needs to be set to cts.Token
options.CancellationToken = cts.Token;
//start a task that will cancel the Parallel for
//after a given time
Task.Factory.StartNew(() =>
{
Thread.Sleep(2000);
cts.Cancel();
//richTextBox1.AppendText("Cancellation requested");
MessageBox.Show("Cancellation Requested");
});
Parallel.For(1, 5000, options, index =>
{
options.CancellationToken.ThrowIfCancellationRequested();
int i = index;
context.Post(obj =>
{
richTextBox1.AppendText(obj + "\n");
richTextBox1.ScrollToCaret();
}, i.ToString());
});
//Ref: ://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.post(v=vs.110).aspx
}
private void Form1_Load(object sender, EventArgs e)
{
//get the synchronizationContext of the UI
context = SynchronizationContext.Current;
}
private void btnCancelParallelFor_Click(object sender, EventArgs e)
{
if (cts != null)
cts.Cancel();
}
}
}
//://msdn.microsoft.com/en-us/library/dd781401(v=vs.110).aspx
//Lab Assignment
//Replace the Parallel.For method by the Parallel.ForEach method
//Do a ForEach without cancellation (just a normal loop)
//Then do a second ForEach with the possibility of cancelling
Labels:
C#Advance
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment