Winform异步解决窗体耗时操作(Action专门用于无返回值,Func专门用于有返回值)

http://blog.csdn.net/config_man/article/details/25578767

[csharp] view plain copy
    1. #region 调用timer控件实时查询开关机时间  
    2. private void timer1_Tick(object sender, EventArgs e)  
    3. {  
    4.     string sql = "SELECT startTime,endTime,AMTusername,AMTpassword,AMTip FROM AmtTiming at, AmtComputer ac WHERE at.cid = ac.id";  
    5.     List<TimingBean> list = new Database().getRS(sql);  
    6.   
    7.     if (list != null && list.Count > 0)  
    8.     {  
    9.         foreach (TimingBean tb in list)  
    10.         {  
    11.             string startTime = tb.StartTime;  
    12.             string endTime = tb.EndTime;  
    13.             string AMTusername = tb.AMTUsername;  
    14.             string AMTpassword = tb.AMTPassword;  
    15.             string AMTip = tb.AMTIp;  
    16.   
    17.             string now = DateTime.Now.ToShortTimeString();  
    18.             if (startTime == now)  
    19.             {  
    20.                 Action<string, string, string, bool> action = new Action<string, string, string, bool>(StartOrShutDown);  
    21.                 action.BeginInvoke(AMTusername, AMTpassword, AMTip, true, null, null);  
    22.             }  
    23.             else if (endTime == now)  
    24.             {  
    25.                 Action<string, string, string, bool> action = new Action<string, string, string, bool>(StartOrShutDown);  
    26.                 action.BeginInvoke(AMTusername, AMTpassword, AMTip, false, null, null);  
    27.             }  
    28.         }  
    29.     }  
    30. }  
    31. private void StartOrShutDown(string user, string pass, string ip, bool isStart)  
    32. {  
    33.     AmtRemoteAControl amtControl = new AmtRemoteAControl();  
    34.     if (isStart)  
    35.     {  
    36.         //如果开机不成功,则让其再执行一次  
    37.         try  
    38.         {  
    39.             amtControl.SendPowerOnCmd(ip, user, pass);  
    40.         }  
    41.         catch  
    42.         {  
    43.             try  
    44.             {  
    45.                 amtControl.SendPowerOnCmd(ip, user, pass);  
    46.             }  
    47.             catch (Exception e)  
    48.             {  
    49.                 MessageBox.Show("终端设备:" + ip + "自动开机失败。异常信息:" + e.Message);  
    50.             }  
    51.         }  
    52.     }  
    53.     else  
    54.     {  
    55.         //如果关机不成功,则让其再执行一次  
    56.         try  
    57.         {  
    58.             amtControl.SendPowerOffCmd(ip, user, pass);  
    59.         }  
    60.         catch  
    61.         {  
    62.             try  
    63.             {  
    64.                 amtControl.SendPowerOffCmd(ip, user, pass);  
    65.             }  
    66.             catch (Exception e)  
    67.             {  
    68.                 MessageBox.Show("终端设备:" + ip + "自动关机失败。异常信息:" + e.Message);  
    69.             }  
    70.         }  
    71.     }  
    72.   
    73. }  
    74. #endregion  
    75.  
    76. #region 开关机、重启 "查询按钮"  
    77. bool has = false;  
    78. private void button1_Click(object sender, EventArgs e)  
    79. {  
    80.       
    81.     //获得省份索引和某个市的文本  
    82.     int index = this.comboBox1.SelectedIndex;  
    83.   
    84.     if (0 == index)  
    85.     {  
    86.         MessageBox.Show("请选择区域!"); return;  
    87.     }  
    88.     else  
    89.     {  
    90.         #region 获取选择的区域  
    91.         this.buttonStart.Enabled = false;  
    92.         this.buttonShutdown.Enabled = false;  
    93.         this.buttonReStart.Enabled = false;  
    94.   
    95.         string place = this.comboBox1.Text;              //省  
    96.   
    97.         int city_index = this.comboBox2.SelectedIndex;//市  
    98.         string county = this.comboBox3.Text;        //区县  
    99.   
    100.         //如果城市有选择  
    101.         if (city_index != 0)  
    102.         {  
    103.             place = place + this.comboBox2.Text;  
    104.         }  
    105.         //如果区县有选择  
    106.         if ((null != county) && (!((string.Empty).Equals(county))) && (!"--请选择--".Equals(county)))  
    107.         {  
    108.             place = place + county;  
    109.         }  
    110.         #endregion  
    111.   
    112.         try  
    113.         {  
    114.             #region 将查到的设备信息绑定到数据表格  
    115.             //将查到的设备信息绑定到数据表格  
    116.             //string sql = "SELECT '' as '选择',cp.en '设备编号',cp.ip '设备IP',cp.place '设备地址', cp.AMTusername '用户名',cp.AMTpassword '密码',cp.AMTip 'IP',cp.id '主键',cp.status '状态' FROM AmtComputer cp WHERE cp.place like '%" + place + "%'";  
    117.             string sql = "SELECT cp.en '设备编号',cp.ip '设备IP',cp.place '设备地址', cp.AMTusername '用户名',cp.AMTpassword '密码',cp.AMTip 'IP',cp.id '主键',cp.status '状态' FROM AmtComputer cp WHERE cp.place like '%" + place + "%'";  
    118.   
    119.             Database db = new Database();  
    120.             DataSet ds = db.getDS(new DataSet(), sql);  
    121.             DataTable table = ds.Tables["data"];  
    122.             this.bindingSource1.DataSource = table;  
    123.             this.dataGridView1.DataSource = this.bindingSource1;  
    124.   
    125.             if(!has)  
    126.             {  
    127.                 //添加复选框  
    128.                 DataGridViewCheckBoxColumn box = new DataGridViewCheckBoxColumn();  
    129.                 box.HeaderText = "选择";  
    130.                 box.Name = "选择";  
    131.                 this.dataGridView1.Columns.Insert(0, box);  
    132.                 has = true;  
    133.             }  
    134.   
    135.             //设置部分列为不可见状态  
    136.             this.dataGridView1.Columns["用户名"].Visible = false;//AMT用户名  
    137.             this.dataGridView1.Columns["密码"].Visible = false;//AMT密码  
    138.             this.dataGridView1.Columns["IP"].Visible = false;//AMT设备ip  
    139.             this.dataGridView1.Columns["主键"].Visible = false;//主键  
    140.   
    141.             this.dataGridView1.Columns["选择"].Width = 60;//复选框  
    142.             this.dataGridView1.Columns["设备编号"].Width = 100;//设备编号  
    143.             this.dataGridView1.Columns["设备IP"].Width = 140;//设备IP  
    144.             this.dataGridView1.Columns["设备地址"].Width = 160;//设备地址  
    145.             this.dataGridView1.Columns["状态"].Width = 180;//状态  
    146.  
    147.             #endregion  
    148.   
    149.             //this.labelState.Text = "正在获取设备状态,请稍后...";  
    150.             //this.Refresh();  
    151.             int count = table.Rows.Count;  
    152.             for (int i = 0; i < count; i++)  
    153.             {  
    154.                 string username = table.Rows[i]["用户名"].ToString(); //amt用户名  
    155.                 string password = table.Rows[i]["密码"].ToString(); //amt密码  
    156.                 string host = table.Rows[i]["IP"].ToString();     //amtIP地址  
    157.   
    158.                 this.dataGridView1.Rows[i].Cells["状态"].Value = "正在获取终端状态...";  
    159.                 this.dataGridView1.Rows[i].Cells["状态"].Style.ForeColor = Color.Red;  
    160.                 this.dataGridView1.Rows[i].Cells["状态"].Style.Font = new Font("宋体", 11F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));  
    161.   
    162.                 Func<int, string, string, string, string> func = new Func<int, string, string, string, string>(getPowerState);  
    163.                 func.BeginInvoke(i, username, password, host,  
    164.                                                         (result) =>  
    165.                                                         {  
    166.                                                             string state = func.EndInvoke(result);  
    167.                                                             this.BeginInvoke(new Action<string>(setStateValue), state);  
    168.                                                         }, null);  
    169.             }  
    170.         }  
    171.         catch (Exception ee) { MessageBox.Show(ee.Message); }  
    172.     }  
    173. }   
    174. private void setStateValue(string state)  
    175. {  
    176.     string[] array = state.Split(',');  
    177.     this.dataGridView1.Rows[Convert.ToInt16(array[0])].Cells["状态"].Value = array[1];  
    178.     this.buttonStart.Enabled = true;  
    179.     this.buttonShutdown.Enabled = true;  
    180.     this.buttonReStart.Enabled = true;  
    181. }  
    182. #endregion  
    183.  
    184. #region 获取amt设备的当前电源状态  
    185. private string getPowerState(int index,string username, string password, string host)  
    186. {     
    187.     ConnectionInfo info = new ConnectionInfo(host, username, password, false,  
    188.                                            string.Empty, ConnectionInfo.AuthMethod.Digest,  
    189.                                            null, null);  
    190.     DotNetWSManClient wsman = new DotNetWSManClient(info);  
    191.   
    192.     RemoteControlApi api = new RemoteControlApi(wsman);  
    193.     try  
    194.     {  
    195.         CIM_AssociatedPowerManagementService service = api.GetCurrentPowerState(true);  
    196.         ushort state = service.PowerState;  
    197.         if (state == 2)  
    198.         {  
    199.             return index + ",开机";  
    200.         }  
    201.         else if (state == 8)  
    202.         {  
    203.             return index + ",关机";  
    204.         }  
    205.     }  
    206.     catch  
    207.     {  
    208.         try  
    209.         {  
    210.             CIM_AssociatedPowerManagementService service = api.GetCurrentPowerState(false);  
    211.             ushort state = service.PowerState;  
    212.             if (state == 2)  
    213.             {  
    214.                 return index + ",开机";  
    215.             }  
    216.             else if (state == 8)  
    217.             {  
    218.                 return index + ",关机";  
    219.             }  
    220.         }  
    221.         catch (Exception e2)  
    222.         {  
    223.             return index + "," + e2.Message;  
    224.         }  
    225.     }  
    226.     return index + ",未知";  
    227. }  
    228. #endregion 
原文地址:https://www.cnblogs.com/LuoEast/p/8605481.html