8,756
社区成员




namespace 多线程方法重入
{
public partial class MainWindow : Window
{
Object lockObj=new Object();
public MainWindow()
{
InitializeComponent();
}
private void bt_Click(object sender, RoutedEventArgs e)
{
ThreadStart a = new ThreadStart(Cout);
Thread thread1 = new Thread(a);
thread1.IsBackground = true;
thread1.Start();
ThreadStart b = new ThreadStart(Cout);
Thread thread2 = new Thread(b);
thread2.IsBackground = true;
thread2.Start();
}
public void Cout()
{
lock(lockObj)
{
for (int i = 0; i < 1000;i++)
{
Dispatcher.Invoke(new Action(() =>
{
int a = int.Parse(TB.Text);
a++;
TB.Text = a.ToString();
}));
}
}
}
}
}
public void Cout()
{
for (int i = 0; i <= 1000; i++) {
Dispatcher.Invoke(new Action(() =>
{
TB.Text = i.ToString();
}));
}
}
public void Cout()
{
for (int i = 1; i <= 1000; i++)
{
Dispatcher.Invoke(new Action(() =>
{
//int a = int.Parse(TB.Text);
//a++;
TB.Text = i.ToString();
if (i == 1000)
{
MessageBox.Show("");
}
}));
}
}
其实我是想知道 int a = int.Parse(TB.Text);的意思啊。为什么要有a来技术呢。这个有特别需求?
if语句是debug用的。可以不要
private string val;
private void bt_Click(object sender, RoutedEventArgs e)
{
val = TB.Text;
ThreadStart a = new ThreadStart(Cout);
Thread thread1 = new Thread(a);
thread1.IsBackground = true;
thread1.Start();
ThreadStart b = new ThreadStart(Cout);
Thread thread2 = new Thread(b);
thread2.IsBackground = true;
thread2.Start();
}
public void Cout()
{
int result = 0;
result = int.Parse(val);
for (int i = 0; i < 1000; i++)
{
result++;
}
//在这里进行
Application.Current.Dispatcher.Invoke(new Action(() =>
{
//code进行前台的更新
xxx.Text = result.ToString();
}), null);
}
Dispatcher.Invoke(new Action(() =>
{
int a = int.Parse(TB.Text);
a++;
TB.Text = a.ToString();
}));
你这里的代码有问题~,你只是for循环的过程是有多线程来操作,但是每个取值和赋值的过程,其实都是主线程也就是UI线程在做,所以,你其实跟没有使用多线程一样~
Dispatcher.Invoke的意思就是交给主线程来处理,所以当你主线程在处理第一个线程发起的请求时,第二个线程肯定是在阻塞的以等待主线程处理完第一个线程中的请求,再来出来第二个的