AsyncCallback The Windows Control
在项目中经常有装入大批量数据,需要显示进度。
但Windows Control不是线程安全的。
在装库过程中,可能要对Control进行操作,此时,如果随意拖动窗体。
主进程就无法进行对Control的Redraw.
所以就要采用异步的方法。
private SortedList sl = null;
private const int TEST_COUNT = 10000;
private const int TEST_COUNT = 10000;
private void button1_Click(object sender, System.EventArgs e)
{
mi = new MethodInvoker(DoWork);
mi.BeginInvoke(new AsyncCallback(DoneWork), null);
}
private void DoWork()
{
sl = new SortedList();
InitialPB(TEST_COUNT);
for (int i =0;i<TEST_COUNT;i++)
{
sl.Add(i,"NoWay" + i.ToString());
Thread.Sleep(100);
RefreshText("NoWay" + i.ToString());
RefreshPB(1);
}
}
private void InitialPB(int max)
{
if( InvokeRequired )
{
this.Invoke( new IntDelegate(InitialPB), new object [] { max } );
return ;
}
{
mi = new MethodInvoker(DoWork);
mi.BeginInvoke(new AsyncCallback(DoneWork), null);
}
private void DoWork()
{
sl = new SortedList();
InitialPB(TEST_COUNT);
for (int i =0;i<TEST_COUNT;i++)
{
sl.Add(i,"NoWay" + i.ToString());
Thread.Sleep(100);
RefreshText("NoWay" + i.ToString());
RefreshPB(1);
}
}
private void InitialPB(int max)
{
if( InvokeRequired )
{
this.Invoke( new IntDelegate(InitialPB), new object [] { max } );
return ;
}
progressBar1.Maximum = max ;
progressBar1.Value = 0;
}
progressBar1.Value = 0;
}
private void RefreshText(string item)
{
if( InvokeRequired )
{
this.Invoke( new StringDelegate(RefreshText), new object [] { item } );
return ;
}
{
if( InvokeRequired )
{
this.Invoke( new StringDelegate(RefreshText), new object [] { item } );
return ;
}
this.textBox1.Text = item;
}
}
private void RefreshPB(int Value)
{
if( InvokeRequired )
{
this.Invoke( new IntDelegate(RefreshPB), new object [] {Value} );
return ;
}
{
if( InvokeRequired )
{
this.Invoke( new IntDelegate(RefreshPB), new object [] {Value} );
return ;
}
progressBar1.Value+=Value;
}
}
private void DoneWork(IAsyncResult result)
{
if( InvokeRequired )
{
Invoke(new AsyncCallback(DoneWork), new Object [] { result } );
return ;
}
MessageBox.Show("Done!");
}
{
if( InvokeRequired )
{
Invoke(new AsyncCallback(DoneWork), new Object [] { result } );
return ;
}
MessageBox.Show("Done!");
}
private void button2_Click(object sender, System.EventArgs e)
{
mi.EndInvoke(null);
}
{
mi.EndInvoke(null);
}
private MethodInvoker mi= null;
private delegate void IntDelegate(int num);
private delegate void StringDelegate(string str);
private delegate void StringDelegate(string str);