Timer Tick 事件传参 简单实用

今天有个需求就是定时关闭远程物理机,因为权限问题,后来只能在本地实现延迟关机。当中涉及到Timer 的tick事件,因为要给Tick事件传递自定义阐述(因引用类库不同,有的是Tick事件,有的是 Elapsed),废话不多说。下面介绍如何给Tick事件传递自己的参数:

1、定义全局变量(这样太low,如果要放在循环里面执行的话,那就更low了)

2、自定义一个父类,集成Timer,在里面定义属性字段,然后赋值传递。这方法还行,但是我觉得还不够简单。

3、直接通过lambda 表达式,实现传递。看如下代码实现:


Timer timer = new Timer();
                timer.Interval = 60000;
                timer.Elapsed += new ElapsedEventHandler((o, e) => Timer_Tick(o, e, strIP,strUser,strPwd));
                timer.Start();
                isOk = true;
private static void Timer_Tick(object sender, EventArgs e, string strIP, string strUser, string strPwd)
        {
            ConnectionOptions options = new ConnectionOptions();
            options.Impersonation = ImpersonationLevel.Impersonate;
            options.EnablePrivileges = true;
            options.Username = strUser;
            options.Password = strPwd;
            ManagementScope scope = new ManagementScope("\\\\" + strIP + "\\root\\cimv2", options);
            try
            {
                //用给定管理者用户名和口令连接远程的计算机
                scope.Connect();
                ObjectQuery oq = new ObjectQuery("select * from win32_OperatingSystem");
                ManagementObjectSearcher query1 = new ManagementObjectSearcher(scope, oq);
                ManagementObjectCollection queryCollection1 = query1.Get();
                foreach (ManagementObject mo in queryCollection1)
                {
                    object[] ss = { "1", "4" };
                   
                    var ob = mo.InvokeMethod("shutdown", ss);
                    ((Timer)sender).Stop();

                }
            }
            catch (Exception er)
            {
                Console.WriteLine("连接"+strIP+" 出错,出错信息为:" + er.Message);
            }
        }

阅读更多
换一批

没有更多推荐了,返回首页