Winform异步解决窗体耗时操作(Action专门用于无返回值,Func专门用于有返回值)
http://blog.csdn.net/config_man/article/details/25578767
- #region 调用timer控件实时查询开关机时间
- private void timer1_Tick(object sender, EventArgs e)
- {
- string sql = "SELECT startTime,endTime,AMTusername,AMTpassword,AMTip FROM AmtTiming at, AmtComputer ac WHERE at.cid = ac.id";
- List<TimingBean> list = new Database().getRS(sql);
- if (list != null && list.Count > 0)
- {
- foreach (TimingBean tb in list)
- {
- string startTime = tb.StartTime;
- string endTime = tb.EndTime;
- string AMTusername = tb.AMTUsername;
- string AMTpassword = tb.AMTPassword;
- string AMTip = tb.AMTIp;
- string now = DateTime.Now.ToShortTimeString();
- if (startTime == now)
- {
- Action<string, string, string, bool> action = new Action<string, string, string, bool>(StartOrShutDown);
- action.BeginInvoke(AMTusername, AMTpassword, AMTip, true, null, null);
- }
- else if (endTime == now)
- {
- Action<string, string, string, bool> action = new Action<string, string, string, bool>(StartOrShutDown);
- action.BeginInvoke(AMTusername, AMTpassword, AMTip, false, null, null);
- }
- }
- }
- }
- private void StartOrShutDown(string user, string pass, string ip, bool isStart)
- {
- AmtRemoteAControl amtControl = new AmtRemoteAControl();
- if (isStart)
- {
- //如果开机不成功,则让其再执行一次
- try
- {
- amtControl.SendPowerOnCmd(ip, user, pass);
- }
- catch
- {
- try
- {
- amtControl.SendPowerOnCmd(ip, user, pass);
- }
- catch (Exception e)
- {
- MessageBox.Show("终端设备:" + ip + "自动开机失败。异常信息:" + e.Message);
- }
- }
- }
- else
- {
- //如果关机不成功,则让其再执行一次
- try
- {
- amtControl.SendPowerOffCmd(ip, user, pass);
- }
- catch
- {
- try
- {
- amtControl.SendPowerOffCmd(ip, user, pass);
- }
- catch (Exception e)
- {
- MessageBox.Show("终端设备:" + ip + "自动关机失败。异常信息:" + e.Message);
- }
- }
- }
- }
- #endregion
- #region 开关机、重启 "查询按钮"
- bool has = false;
- private void button1_Click(object sender, EventArgs e)
- {
- //获得省份索引和某个市的文本
- int index = this.comboBox1.SelectedIndex;
- if (0 == index)
- {
- MessageBox.Show("请选择区域!"); return;
- }
- else
- {
- #region 获取选择的区域
- this.buttonStart.Enabled = false;
- this.buttonShutdown.Enabled = false;
- this.buttonReStart.Enabled = false;
- string place = this.comboBox1.Text; //省
- int city_index = this.comboBox2.SelectedIndex;//市
- string county = this.comboBox3.Text; //区县
- //如果城市有选择
- if (city_index != 0)
- {
- place = place + this.comboBox2.Text;
- }
- //如果区县有选择
- if ((null != county) && (!((string.Empty).Equals(county))) && (!"--请选择--".Equals(county)))
- {
- place = place + county;
- }
- #endregion
- try
- {
- #region 将查到的设备信息绑定到数据表格
- //将查到的设备信息绑定到数据表格
- //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 + "%'";
- 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 + "%'";
- Database db = new Database();
- DataSet ds = db.getDS(new DataSet(), sql);
- DataTable table = ds.Tables["data"];
- this.bindingSource1.DataSource = table;
- this.dataGridView1.DataSource = this.bindingSource1;
- if(!has)
- {
- //添加复选框
- DataGridViewCheckBoxColumn box = new DataGridViewCheckBoxColumn();
- box.HeaderText = "选择";
- box.Name = "选择";
- this.dataGridView1.Columns.Insert(0, box);
- has = true;
- }
- //设置部分列为不可见状态
- this.dataGridView1.Columns["用户名"].Visible = false;//AMT用户名
- this.dataGridView1.Columns["密码"].Visible = false;//AMT密码
- this.dataGridView1.Columns["IP"].Visible = false;//AMT设备ip
- this.dataGridView1.Columns["主键"].Visible = false;//主键
- this.dataGridView1.Columns["选择"].Width = 60;//复选框
- this.dataGridView1.Columns["设备编号"].Width = 100;//设备编号
- this.dataGridView1.Columns["设备IP"].Width = 140;//设备IP
- this.dataGridView1.Columns["设备地址"].Width = 160;//设备地址
- this.dataGridView1.Columns["状态"].Width = 180;//状态
- #endregion
- //this.labelState.Text = "正在获取设备状态,请稍后...";
- //this.Refresh();
- int count = table.Rows.Count;
- for (int i = 0; i < count; i++)
- {
- string username = table.Rows[i]["用户名"].ToString(); //amt用户名
- string password = table.Rows[i]["密码"].ToString(); //amt密码
- string host = table.Rows[i]["IP"].ToString(); //amtIP地址
- this.dataGridView1.Rows[i].Cells["状态"].Value = "正在获取终端状态...";
- this.dataGridView1.Rows[i].Cells["状态"].Style.ForeColor = Color.Red;
- this.dataGridView1.Rows[i].Cells["状态"].Style.Font = new Font("宋体", 11F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
- Func<int, string, string, string, string> func = new Func<int, string, string, string, string>(getPowerState);
- func.BeginInvoke(i, username, password, host,
- (result) =>
- {
- string state = func.EndInvoke(result);
- this.BeginInvoke(new Action<string>(setStateValue), state);
- }, null);
- }
- }
- catch (Exception ee) { MessageBox.Show(ee.Message); }
- }
- }
- private void setStateValue(string state)
- {
- string[] array = state.Split(',');
- this.dataGridView1.Rows[Convert.ToInt16(array[0])].Cells["状态"].Value = array[1];
- this.buttonStart.Enabled = true;
- this.buttonShutdown.Enabled = true;
- this.buttonReStart.Enabled = true;
- }
- #endregion
- #region 获取amt设备的当前电源状态
- private string getPowerState(int index,string username, string password, string host)
- {
- ConnectionInfo info = new ConnectionInfo(host, username, password, false,
- string.Empty, ConnectionInfo.AuthMethod.Digest,
- null, null);
- DotNetWSManClient wsman = new DotNetWSManClient(info);
- RemoteControlApi api = new RemoteControlApi(wsman);
- try
- {
- CIM_AssociatedPowerManagementService service = api.GetCurrentPowerState(true);
- ushort state = service.PowerState;
- if (state == 2)
- {
- return index + ",开机";
- }
- else if (state == 8)
- {
- return index + ",关机";
- }
- }
- catch
- {
- try
- {
- CIM_AssociatedPowerManagementService service = api.GetCurrentPowerState(false);
- ushort state = service.PowerState;
- if (state == 2)
- {
- return index + ",开机";
- }
- else if (state == 8)
- {
- return index + ",关机";
- }
- }
- catch (Exception e2)
- {
- return index + "," + e2.Message;
- }
- }
- return index + ",未知";
- }
- #endregion
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现