zoukankan      html  css  js  c++  java
  • 跨线程操作对象

    引言:同样的操作在单线程中可以运行,在多线程的环境中很可能碰见资源抢占的情况,而.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);
    }

    }

    }

  • 相关阅读:
    关于字符串循环遍历的两种方法
    Think PHP 6 .0 学习笔记
    微信小程序当前页面标题设置
    wx.showActionSheet() 选择菜单
    wx.showLoading() 加载框
    wx.showModal() 相当于 JS中的 confirm()
    wx.showToast() 显示消息提示框
    微信小程序 getLauchOprionsSync()
    怎样查看一个网站由那些服务器提供服务
    通过 bootstrap 创建好看的单选框复选框
  • 原文地址:https://www.cnblogs.com/Robert-huge/p/5501201.html
Copyright © 2011-2022 走看看