zoukankan      html  css  js  c++  java
  • C# winform编程中多线程操作控件方法

     1 private void Form1_Load(object sender, EventArgs e)
     2         {
     3             Thread newthread = new Thread(new ThreadStart(BackgroundProcess));
     4             newthread.Start();
     5  
     6         }
     7  
     8         /// <summary>    
     9         /// 定义一个代理    
    10         /// </summary>    
    11         private delegate void CrossThreadOperationControl();
    12  
    13         private void BackgroundProcess()
    14         {
    15             // 将代理实例化为一个匿名代理    
    16             CrossThreadOperationControl CrossDelete = delegate()
    17             {
    18                 int i = 1;
    19                 while (i < 5)
    20                 {
    21                     // 向列表框增加一个项目    
    22                     listBox1.Items.Add("Item " + i.ToString());
    23                     i++;
    24                 }
    25                 label1.Text = "我在新线程里访问这个lable!";
    26                 listBox1.Items.Add(label1.Text);
    27             };
    28             listBox1.Invoke(CrossDelete);
    29         }

    收集一下,在C# winform编程中多线程操作控件时,可以有下面种方法:

    1. 又看到一种方法(2014.1.6):

    1. 刚看到一种方法(2014.1.5):

     1 private void btnTest_Click(object sender, EventArgs e)
     2         {
     3             if (this.txtIP.Text.Trim() != "" && this.txtPort.Text.Trim() != "")
     4             {
     5                 string proxy = this.txtIP.Text.Trim() + ":" + this.txtPort.Text.Trim();
     6                 string result = string.Empty;
     7                 this.btnTest.Enabled = false;
     8                 new Thread(delegate
     9                 {
    10                     Stopwatch stopwatch = new Stopwatch();
    11                     stopwatch.Start();
    12                     HttpClient httpClient = new HttpClient();
    13                     httpClient.Proxy = new WebProxy(proxy);
    14                     httpClient.TimeOut = 2000;
    15                     object result;
    16                     try
    17                     {
    18                         string a = httpClient.Get("http://www.baidu.com", "", "", "", "", "get");
    19                         if (a != "")
    20                         {
    21                             result = "响应成功!";
    22                         }
    23                         else
    24                         {
    25                             result = "响应失败!";
    26                         }
    27                     }
    28                     catch
    29                     {
    30                     }
    31                     stopwatch.Stop();
    32                     result = result;
    33                     result = string.Concat(new object[]
    34                     {
    35                         result,
    36                         ",响应花费:",
    37                         stopwatch.ElapsedMilliseconds,
    38                         "ms"
    39                     });
    40                     this.BeginInvoke(delegate
    41                     {
    42                         this.lbResult.Text = result;
    43                         this.btnTest.Enabled = true;
    44                     });
    45                 })
    46                 {
    47                     IsBackground = true
    48                 }.Start();
    49             }
    50             else
    51             {
    52                 this.lbResult.Text = "请输入完整再提交!";
    53             }
    54         }

    1. 直接使用表达式和Action()

     1 private void btnInitEnv_Click(object sender, EventArgs e)
     2         {
     3             //初始化环境时回显出来的文字不让看
     4             try
     5             {
     6                 this.textBoxOutPut.Clear();
     7                 this.btnInitEnv.Enabled = false;
     8                 this.labelStateInfo.Text = "";
     9                 this.labelStateInfo.ForeColor = Color.Red;
    10 
    11                 if (!WriteToSerialPort("diags"))
    12                 {
    13                     this.btnInitEnv.Enabled = true;
    14                     return;
    15                 }
    16 
    17                 Thread thread = new Thread(new ThreadStart(() =>
    18                 {
    19                     int i = 0;
    20                     bool flagFind = false;
    21                     StringBuilder sb = new StringBuilder();
    22 
    23                     while (true)
    24                     {
    25                         Thread.Sleep(300);
    26                         this.Invoke(new Action(() =>
    27                         {
    28                             sb.Append(this.textBoxOutPut.Text);
    29                             this.textBoxOutPut.Clear();
    30                             if (sb.ToString().Contains("Entering recovery mode, starting command prompt"))
    31                             {
    32                                 this.textBoxOutPut.AppendText(string.Format(PubilcConstVar.TerimalStrFormat,
    33                                     DateTime.Now.ToString(PubilcConstVar.TimeFormat),
    34                                     "Entering recovery mode, starting command prompt, Stop.
    "));
    35                                 this.labelStateInfo.ForeColor = Color.Red;
    36                                 this.labelStateInfo.Text = "初始化失败,请手动输入命令初始化";
    37                                 flagFind = true;
    38                                 this.btnInitEnv.Enabled = true;
    39                             }
    40                             else if (sb.ToString().Contains(":-)"))
    41                             {
    42                                 this.textBoxOutPut.AppendText(string.Format(PubilcConstVar.TerimalStrFormat,
    43                                     DateTime.Now.ToString(PubilcConstVar.TimeFormat),
    44                                     "进入操作模式成功
    "));
    45                                 this.labelStateInfo.ForeColor = Color.Blue;
    46                                 this.labelStateInfo.Text = "初始化成功";
    47                                 flagFind = true;
    48 
    49                                 //将业务按钮使能
    50                                 EnableBussinessButtons();
    51                             }
    52                         }));
    53 
    54                         if (flagFind || ++i > 20) //找开标志或10秒超时中断
    55                         {
    56                             break;
    57                         }
    58                     }
    59 
    60                     if (!flagFind)
    61                     {
    62                         this.Invoke(new Action(() =>
    63                         {
    64                             this.textBoxOutPut.Clear();
    65                             this.labelStateInfo.ForeColor = Color.Red;
    66                             this.labelStateInfo.Text = "初始化失败,超时";
    67                             this.btnInitEnv.Enabled = true;
    68 
    69                             DisableBussinessButtons();
    70                         }));
    71                     }
    72                 }));
    73 
    74                 thread.IsBackground = true;
    75                 thread.Start();
    76             }
    77             catch (Exception ex)
    78             {
    79                 this.log.Write(ex.ToString());
    80             }
    81         }

    2. 使用线程函数加action()

     1 private void btnInitEnv_Click(object sender, EventArgs e)
     2         {
     3             //初始化环境时回显出来的文字不让看
     4             try
     5             {
     6                 this.textBoxOutPut.Clear();
     7                 this.btnInitEnv.Enabled = false;
     8                 this.labelStateInfo.Text = "";
     9                 this.labelStateInfo.ForeColor = Color.Red;
    10 
    11                 if (!WriteToSerialPort("diags"))
    12                 {
    13                     this.btnInitEnv.Enabled = true;
    14                     return;
    15                 }
    16 
    17                 Thread thread = new Thread(new ThreadStart(MonitorOutPutThread));
    18 
    19                 thread.IsBackground = true;
    20                 thread.Start();
    21             }
    22             catch (Exception ex)
    23             {
    24                 this.log.Write(ex.ToString());
    25             }
    26         }

       线程函数:

     1 private void MonitorOutPutThread()
     2         {
     3             int i = 0;
     4             bool flagFind = false;
     5             StringBuilder sb = new StringBuilder();
     6 
     7             while (true)
     8             {
     9                 Thread.Sleep(300);
    10                 this.Invoke(new Action(() =>
    11                 {
    12                     sb.Append(this.textBoxOutPut.Text);
    13                     this.textBoxOutPut.Clear();
    14                     if (sb.ToString().Contains("Entering recovery mode, starting command prompt"))
    15                     {
    16                         this.textBoxOutPut.AppendText(string.Format(PubilcConstVar.TerimalStrFormat,
    17                             DateTime.Now.ToString(PubilcConstVar.TimeFormat),
    18                             "Entering recovery mode, starting command prompt, Stop.
    "));
    19                         this.labelStateInfo.ForeColor = Color.Red;
    20                         this.labelStateInfo.Text = "初始化失败,请手动输入命令初始化";
    21                         flagFind = true;
    22                         this.btnInitEnv.Enabled = true;
    23                     }
    24                     else if (sb.ToString().Contains(":-)"))
    25                     {
    26                         this.textBoxOutPut.AppendText(string.Format(PubilcConstVar.TerimalStrFormat,
    27                             DateTime.Now.ToString(PubilcConstVar.TimeFormat),
    28                             "进入操作模式成功
    "));
    29                         this.labelStateInfo.ForeColor = Color.Blue;
    30                         this.labelStateInfo.Text = "初始化成功";
    31                         flagFind = true;
    32 
    33                         //将业务按钮使能
    34                         EnableBussinessButtons();
    35                     }
    36                 }));
    37 
    38                 if (flagFind || ++i > 20) //找开标志或10秒超时中断
    39                 {
    40                     break;
    41                 }
    42             }
    43 
    44             if (!flagFind)
    45             {
    46                 this.Invoke(new Action(() =>
    47                 {
    48                     this.textBoxOutPut.Clear();
    49                     this.labelStateInfo.ForeColor = Color.Red;
    50                     this.labelStateInfo.Text = "初始化失败,超时";
    51                     this.btnInitEnv.Enabled = true;
    52 
    53                     DisableBussinessButtons();
    54                 }));
    55             }
    56         }

    3. 就是使用委托,这个网上例子很多,不再实现

  • 相关阅读:
    结构体和枚举
    [转载]玩转Asp.net MVC 的八个扩展点
    SQLServer处理亿万级别的数据的优化措施
    Lambda表达式
    匿名类型
    单例模式——懒汉式和饿汉式详解
    Cglib动态代理实现原理
    集合的子集
    深入剖析ThreadLocal
    java注解的自定义和使用
  • 原文地址:https://www.cnblogs.com/kernel0815/p/3463632.html
Copyright © 2011-2022 走看看