These codes generates us this error:
Cross-thread operation not valid: Control 'progressBar2' accessed from a thread other than the thread it was created on.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace ThreadingTest1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
ThreadStart ts1;
ThreadStart ts2;
Thread t1;
Thread t2;
private void btnStart_Click(object sender, EventArgs e)
{
ts1 = new ThreadStart(z1);
ts2 = new ThreadStart(z2);
t1 = new Thread(ts1);
t2 = new Thread(ts2);
t1.Start();
t2.Start();
btnStart.Enabled = false;
}
public void z1()
{
for (int i = 1; i < 60; ++i)
{
progressBar1.Value += 1;
for (int j = 1; j < 10000000; ++j)
{
j += 1;
}
}
}
public void z2()
{
for (int k = 1; k < 100; ++k)
{
progressBar2.Value += 1;
for (int j = 1; j < 25000000; ++j)
{
j += 1;
}
}
}
private void btnstop_Click(object sender, EventArgs e)
{
t1.Suspend();
t2.Suspend();
}
private void btnContinue_Click(object sender, EventArgs e)
{
t1.Resume();
t2.Resume();
}
private void btnClose_Click(object sender, EventArgs e)
{
if (t1.IsAlive)
{
MessageBox.Show("Çalışan threadler var program sonlanamaz.");
}
else
{
this.Close();
}
}
}
}