Can any one help me with the error in this line.
I am trying to build a TPL Multi - Threading application and my intention is to have a start stop button. On click on start the loop will start and like a counter it will display values one by one in the textbox.
and at any point of time if the user clicks on stop button, the task will stop.
Please see the below code for more reference.
Form1.cs:
namespace MultiThreading_Start_Stop_Counter
{
public partial class Form1 : Form
{
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken token = cancellationTokenSource.Token;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Task task = new Task(() =>
{
for (int i = 0; i < 10; i++)
{
if (token.IsCancellationRequested)
{
textBox1.Text = Convert.ToString(0);
return;
}
textBox1.Text = Convert.ToString(i);
}
}, token);
task.Start();
}
private void button2_Click(object sender, EventArgs e)
{
cancellationTokenSource.Cancel();
}
private void button3_Click(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
}
}
}
EDIT: Form1.cs:
namespace MultiThreading_Start_Stop_Counter
{
public partial class Form1 : Form
{
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken token = cancellationTokenSource.Token;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Task task = new Task(() =>
{
for (int i = 0; i < 10; i++)
{
if (token.IsCancellationRequested)
{
textBox1.Text = Convert.ToString(0);
return;
}
textBox1.Text = Convert.ToString(i);
}
}, token);
task.Start();
}
private void button2_Click(object sender, EventArgs e)
{
cancellationTokenSource.Cancel();
}
private void button3_Click(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
}
}
}
Now am getting this exception: **An exception of type
System.InvalidOperationException' occurred in System.Windows.Forms.dll but was not handled in user code. Additional information: Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on.**