有人可以帮助我如何在我的类中设置 Thread.join() 方法,或者是否有一种巧妙的方法来处理SynchronizationContext
类和thread.join
方法。基本上,我试图从不同的线程(不是 UI 线程)每 2 秒更新一次数据网格视图(dgv)单元格和进度条(pb)。当一个线程完成工作时,该功能可以正常工作;但是,我想设置 2 个线程,以便第一个线程(线程 1)将更新控件(在我的情况下,它将更新 datagridview 并显示 10 行,进度条将更新为 50%)。一旦线程 1 完成其工作,线程 2 应该启动并更新控件(在我的情况下,它将更新 datagridview 并显示 10 更多行,进度条将更新为 100%)。请看下面的代码。
using System;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
namespace DelegatesAndCallback
{
public partial class Form1 : Form
{
private Thread newThread1;
private Thread newThread2;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int id = Thread.CurrentThread.ManagedThreadId;
Trace.WriteLine("Button thread "+id);
SynchronizationContext uiContext = SynchronizationContext.Current;
// thread #1
startThread1(uiContext);
// thread #2
startThread2(uiContext);
}
public void startThread1(SynchronizationContext sc)
{
// thread #1
newThread1 = new Thread(Process1) { Name = "Thread 1" };
newThread1.Start(sc);
//newThread1.Join();
}
public void startThread2(SynchronizationContext sc)
{
// thread #2
newThread2 = new Thread(Process2) { Name = "Thread 2" };
newThread2.Start(sc);
//newThread2.Join();
}
public void updateProgressBarValue(object state)
{
double val = Convert.ToDouble(state)/19.0;
pb.Value = (int)(100*val);
}
public void updateDataGridViewValue(object state)
{
dgv.Rows.Add((int) state, (int) state);
}
public void Process1(object state)
{
SynchronizationContext uiContext = state as SynchronizationContext;
for (int i = 0; i < 10; i++)
{
uiContext.Send(updateDataGridViewValue, i);
uiContext.Send(updateProgressBarValue, i);
Thread.Sleep(2000);
}
}
public void Process2(object state)
{
SynchronizationContext uiContext = state as SynchronizationContext;
for (int i = 10; i < 20; i++)
{
if (uiContext != null) uiContext.Send(updateProgressBarValue, i);
if (uiContext != null) uiContext.Send(updateDataGridViewValue, i);
Thread.Sleep(2000);
}
}
}
}