【问题标题】:I am trying to do wmi queries as tasks against several servers using C# threading (tasks)我正在尝试使用 C# 线程(任务)对多个服务器执行 wmi 查询作为任务
【发布时间】:2022-10-14 06:46:41
【问题描述】:

我有一个包含所有服务器名称的文本框,我在 textbox.Lines 中做了一个 foreach 行。我遇到的问题是如何引用我试图写入的动态创建的标签?我一直在努力解决这个问题,我确定我错过了一些东西......我知道我不能成为第一个想要这样做的人。 这是我创建标签的地方: ''' 公共 System.Windows.Forms.Label AddNewUptimeLabel() {

        System.Windows.Forms.Label UptimeLabel = new System.Windows.Forms.Label();
        UptimeLabel.Top = (A * 28) + PushDown;
        UptimeLabel.Left = 180 + Offset;
        UptimeLabel.Name = "UptimeLabel" + Snames;
        UptimeLabel.Text = UpdateUpTime(Snames).ToString();
        
        this.Controls.Add(UptimeLabel);
        lstServerLabeladded.Add(UptimeLabel);


        return UptimeLabel;
    }'''

这是 WMI 的查询: ''' DateTime UpdateUpTime(string computerName) { //List<System.Threading.Thread> lstThread = new List<System.Threading.Thread>();

        //System.Threading.Thread UptimeThread = new System.Threading.Thread(() =>
        

        var scope = new ManagementScope(string.Format(@"\\{0}\root\cimv2", computerName));
        scope.Connect();
        var query = new ObjectQuery("SELECT LastBootUpTime FROM Win32_OperatingSystem");
        var searcher = new ManagementObjectSearcher(scope, query);
        var firstResult = searcher.Get().OfType<ManagementObject>().First(); //assumes that we do have at least one result
        return ManagementDateTimeConverter.ToDateTime(firstResult["LastBootUpTime"].ToString());


    }'''

这是我试图在任务中引用的内容: '''UptimeLabel.Name = "UptimeLabel" + Snames;'''

如果更改,我想每分钟轮询服务器并更新标签,直到我终止工作。

如果这已被问及并回答,请给我一个链接。我的谷歌搜索中一定没有正确的语法。

【问题讨论】:

    标签: c# multithreading task


    【解决方案1】:

    我找到了解决方案: 当我调用任务时,我将标签名称作为参数传递:

    public static async Task UpTimeAsync(string serverName, System.Windows.Forms.Label labelName, CancellationToken token)

    我对自己很生气,因为这很容易。

    【讨论】:

      猜你喜欢
      • 2016-02-21
      • 2014-08-30
      • 2016-09-20
      • 2018-07-20
      • 2015-06-26
      • 2013-02-13
      • 2014-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多