Adrian Cross
asked on
Pararell Task Library - Parallel.For freezing up
Hello, I'm testing a simple loop using the Task Parallel Library and Parallel.For.
However I'm having some difficulties making this to work. First, the UI will freeze until the loop is finished (cannot move the form around or click any other buttton s).
Therefore, I can't cancel the loop until it's done.
Any ideas on this? I've used a normal For loop and I can get the form to move while it's working but I can't cancel it.
Thanks
However I'm having some difficulties making this to work. First, the UI will freeze until the loop is finished (cannot move the form around or click any other buttton s).
Therefore, I can't cancel the loop until it's done.
Any ideas on this? I've used a normal For loop and I can get the form to move while it's working but I can't cancel it.
private CancellationTokenSource cancelToken = new CancellationTokenSource();
private void button1_Click(object sender, EventArgs e)
{
Task.Factory.StartNew(() => { WriteLog(); });
}
private void WriteLog()
{
ParallelOptions po = new ParallelOptions();
po.CancellationToken = cancelToken.Token;
po.MaxDegreeOfParallelism = System.Environment.ProcessorCount;
try
{
po.CancellationToken.ThrowIfCancellationRequested();
Parallel.For(0, 1000, po, i =>
{
po.CancellationToken.ThrowIfCancellationRequested();
txt_Log.Invoke((Action)delegate
{
txt_Log.AppendText("Line: " + i + "\n");
});
});
this.Invoke((Action)delegate
{
this.Text = "Done";
});
}
catch (OperationCanceledException ex)
{
this.Invoke((Action)delegate
{
this.Text = ex.Message;
});
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
cancelToken.Cancel();
}
}
Thanks
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
To leave time for the events, you could put a call to Thread.Sleep after each Invoke call.
And put those two in a lock statement, because there's no way all parallel tasks are going to be in the Sleep call at the same time otherwise.
Open in new window