您现在的位置是:首页 >

jmeter跨线程调用 C# 跨线程调用TextBox方法浅析

火烧 2022-03-11 02:26:58 1031
C# 跨线程调用TextBox方法浅析 首先来看下面代码 主线程 delegate void SetTextCall ack( tri g text) rivate void SetText( tri

C# 跨线程调用TextBox方法浅析  

jmeter跨线程调用 C# 跨线程调用TextBox方法浅析
    首先来看下面代码     主线程     delegate void SetTextCallback(string text)     private void SetText(string text)    {    if (this textBox InvokeRequired)    {    SetTextCallback d = new SetTextCallback(SetText)     this Invoke(d new object[] { text })     }    else    {    this textBox Text = text;    }    }    private void BtnMainThread_Click(object sender EventArgs e) //主线程调用textBox     {    this textBox Text = Main Thread ;    }    子线程     private void BtnNewThread_Click(object sender EventArgs e) //子线程调用textBox     {    this demoThread = new Thread(new ThreadStart(this NewThreadSet))     this demoThread Start()     }    private void NewThreadSet()    {    this SetText( New Thread )     }    首先需要对 this textBox InvokeRequired 返回值的解释     当主线程调用其所在的方法时返回 False     当子线程调用其所在的方法时返回 True     当单击 主线程调用textBox 时     this textBox InvokeRequired 的返回值为 False     直接执行 else 的代码 textBox 中显示 Main Thread     当单击 子线程调用textBox 时     this textBox InvokeRequired 的返回值为 True     执行    SetTextCallback d = new SetTextCallback(SetText)     this Invoke(d new object[] { text })     这两句代码 其中Invoke的作用是 在拥有控件的基础窗口句柄的线程上 用指定的参数列表执行指定委托     a 在拥有控件的基础窗口句柄的线程上 就是指主线程     b 指定的参数列表 是指的参数 text     c 指定委托 是指 SetText 方法     这样就很容易看出     代码执行到 Invoke 后就会把子线程的参数 New Thread 交给主线程去执行 SetText 方法 此时由于是主线程调用SetText方法 所以this textBox InvokeRequired的返回值为False 直接执行else的代码 textBox 中显示 New Thread lishixinzhi/Article/program/net/201311/12241  
永远跟党走
  • 如果你觉得本站很棒,可以通过扫码支付打赏哦!

    • 微信收款码
    • 支付宝收款码