跨线程操作对象
引言:同样的操作在单线程中可以运行,在多线程的环境中很可能碰见资源抢占的情况,而.NET为我们封装了处理这种情况的方法Invoke。具体应用如下,
Example1:
/// <summary>
/// 将窗体显示在指定的Panel上
/// </summary>
/// <param name="pnParent">显示本窗体的父Parent</param>
public void Show(Panel pnParent)
{
try
{
this.TopLevel = false;
this.Dock = DockStyle.Fill;
//跨线程情形
if (pnParent.InvokeRequired)
{
pnParent.Invoke((MethodInvoker)delegate() { pnParent.Controls.Add(this); });
if (this.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate() { this.Show(); });
}
else
{
this.Show();
}
}
//单线程情形
else
{
pnParent.Controls.Add(this);
this.Show();
}
}
catch (System.Exception ex)
{
TestLog.GetInstance().RecordLog("警情信息栏_Show :" + ex.Message);
}
}
Example2:
/// <summary>
/// 清空相关联系人界面
/// 用于 未匹配到联系人情况下,防止用户数据不统一
/// </summary>
private void InitClearForm()
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(delegate()
{
lbTEL.Visible = true;
}));
}
else
{
lbTEL.Visible = true;
}
}
Example3:
/// <summary>
/// 所有数字键共用同一函数,通过事件参数找到控件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_NUM_Click(object sender, EventArgs e)
{
lock(obj)
{
ButtonX btn = sender as ButtonX;
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(delegate()
{
this.txt_CallNum.Text += btn.Text;
//this.txt_CallNum.Select(this.txt_CallNum.Text.Length, 0);
}));
}
else
{
this.txt_CallNum.Text += btn.Text;
//this.txt_CallNum.Select(this.txt_CallNum.Text.Length, 0);
}
}
}