首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

winform invokerequired==true 示意什么意思的

2012-09-03 
winform invokerequiredtrue 表示什么意思的原本我觉得是判断当前线程是否创建控件线程的,但后来我觉得

winform invokerequired==true 表示什么意思的
原本我觉得是判断当前线程是否创建控件线程的,但后来我觉得不是。
界面只有一个textbox和一个label控件。
代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace pro6
{
  public partial class Form1 : Form
  {
  public Form1()
  {
  InitializeComponent();
  }
  private delegate void FlushClient();//代理
  public int i=0;
  private void Form1_Load(object sender, EventArgs e)
  {
  Thread thread = new Thread(CrossThreadFlush);
  thread.IsBackground = true;
  thread.Start();
  }
  private void CrossThreadFlush()
  {
  while (true)
  {
  //将sleep和无限循环放在等待异步的外面
  Thread.Sleep(1000);
  ThreadFunction();
  }
  }
  private void ThreadFunction()
  {
  if (this.textBox1.InvokeRequired)//等待异步
  {
  FlushClient fc = new FlushClient(ThreadFunction);
  this.Invoke(fc);//通过代理调用刷新方法
  i++;
  }
  else
  {
  this.textBox1.Text = DateTime.Now.ToString();
  i++;
  label1.Text = i.ToString();
  }
  }
   

  }
}
为什么label1先是显示1,之后就是3、5、7、9等等的数,每一个都是加2

[解决办法]
invokerequired==true 是判断当前线程是否是UI线程,true不是UI线程。所以要使用委托。
如果是false则不用使用委托。
[解决办法]
this.BeginInvoke(fc);
[解决办法]

探讨
奇怪的是 label1为什么先是显示1,之后就是3、5、7、9等等的数,每一个都是加2,而不是一开始就每个都是加2?

[解决办法]
C# code
FlushClient fc = new FlushClient(ThreadFunction);  this.Invoke(fc);//通过代理调用刷新方法  i++;
[解决办法]
恩 简单来说就是Invoke是同步,会有阻塞,不会回调。BeginInvoke是异步,可以执行下面的语句。
呵呵 暂时我就这么理解来的
[解决办法]
或者这么理解BeginVoke,执行完毕之后返回到主线程(界面线程)

热点排行