c# - 如何异步调用静态方法

标签 c# asynchronous task

我正在尝试构建一个简单的类,它根据要重启的机器类型调用重启函数。被调用的方法是指包含公共(public)静态方法的库。我想使用 Task 异步调用这些静态方法,以便并行调用重启方法。这是到目前为止的代码:

编辑 按照社区的要求,现在这是同一问题的一个版本,下面的代码正在编译。请注意,您需要 Renci.SshNet lib,并且还需要在您的项目中设置对它的引用。

// libs
using System.IO;
using System.Threading.Tasks;
using System.Collections.Generic;

using Renci.SshNet;



namespace ConsoleApp
{
    class Program
    {


        // Simple Host class
        public class CHost
        {
            public string IP;
            public string HostType;

            public CHost(string inType, string inIP)
            {// constructor
                this.IP         = inIP;
                this.HostType   = inType;
            }
        }



        // Call test function
        static void Main(string[] args)
        {

            // Create a set of hosts
            var HostList = new List<CHost>();
            HostList.Add( new CHost("Machine1", "10.52.0.93"));
            HostList.Add( new CHost("Machine1", "10.52.0.30"));
            HostList.Add( new CHost("Machine2", "10.52.0.34"));


            // Call async host reboot call
            RebootMachines(HostList);
        }




        // Reboot method
        public static async void RebootMachines(List<CHost> iHosts)
        {
            // Locals
            var tasks = new List<Task>();


            // Build list of Reboot calls - as a List of Tasks
            foreach(var host in iHosts)
            {

                if (host.HostType == "Machine1")
                {// machine type 1
                    var task = CallRestartMachine1(host.IP);
                    tasks.Add(task);    // Add task to task list
                }
                else if (host.HostType == "Machine2")
                {// machine type 2
                    var task = CallRestartMachine2(host.IP);
                    tasks.Add(task);    // Add task to task list
                }   
            }


            // Run all tasks in task list in parallel
            await Task.WhenAll(tasks);
        }



        // ASYNC METHODS until here
        private static async Task CallRestartMachine1(string host)
        {// helper method: reboot machines of type 1

            // The compiler complains here (RebootByWritingAFile is a static method)
            // Error: "This methods lacks await operators and will run synchronously..."
            RebootByWritingAFile(@"D:\RebootMe.bm","reboot");

        }
        private static async Task CallRestartMachine2(string host)
        {// helper method: reboot machines of type 2

            // The compiler warns here (RebootByWritingAFile is a static method)
            // Error: "This methods lacks await operators and will run synchronously..."
            RebootByNetwork(host,"user","pwd");

        }




        // STATIC METHODS here, going forward
        private static void RebootByWritingAFile(string inPath, string inText)
        {// This method does a lot of checks using more static methods, but then only writes a file


            try
            {
                File.WriteAllText(inPath, inText); // static m
            }
            catch
            {
                // do nothing for now
            }
        }
        private static void RebootByNetwork(string host, string user, string pass)
        {
            // Locals
            string rawASIC = "";
            SshClient SSHclient;
            SshCommand SSHcmd;


            // Send reboot command to linux machine
            try
            {
                SSHclient = new SshClient(host, 22, user, pass);
                SSHclient.Connect();
                SSHcmd = SSHclient.RunCommand("exec /sbin/reboot");
                rawASIC = SSHcmd.Result.ToString();
                SSHclient.Disconnect();
                SSHclient.Dispose();
            }
            catch
            {
                // do nothing for now
            }
        }




    }
}

到目前为止,我对这个设置的唯一问题是静态方法被立即(顺序)调用并且没有分配给任务。例如行

        ...
        else if (host.HostType == "Machine2")
        {// machine type 2
            var task = CallRestartMachine2(host.IP);
            tasks.Add(task);    // Add task to task list
        }  
        ...

如果主机不可访问,需要 20 秒执行。如果 10 台主机不可访问,则连续持续时间为 20*10 = 200 秒。

我知道一些看似相似的问题,例如

但是,引用的 lambda 表达式仍然给我留下相同的编译器错误 ["This methods lacks await operators..."]。此外,我不想生成显式线程 (new Thread(() => ...)),因为如果在集群中重新启动大量机器会产生高开销。

我可能需要重启集群中的大量机器。因此我的问题是:如何更改我的构造以便能够并行调用上述静态方法

编辑 感谢@JohanP 和@MickyD 的评论,我想详细说明我实际上已经尝试编写两种静态方法的异步版本。然而,这让我陷入了困境,每次在异步方法中调用静态方法时,我都会收到编译器警告,该调用将是同步的。这是我如何尝试将对方法的调用包装为异步任务的示例,希望以异步方式调用依赖方法。

private static async Task CallRestartMachine1(string host)
{// helper method: reboot machines of type 1

    // in this version, compiler underlines '=>' and states that 
    // method is still called synchronously
    var test = await Task.Run(async () =>
    {
        RebootByWritingAFile(host);
    });

}

有没有办法包装静态方法调用,使得所有静态子方法都不需要全部重写为异步?

提前谢谢大家。

最佳答案

您的代码奇怪地混合了 async 和 continuations,它甚至无法编译。你需要让它一直async。当您调用 RebootMachines(...) 并且该调用无法被 await 时,您可以安排继续执行,即 RebootMachines(...)。 ContinueWith(t=> Console.WriteLine('All Done'))

public static async Task RebootMachines(List<CHost> iHosts)
{
    var tasks = new List<Task>();

    // Build list of Reboot calls - as a List of Tasks
    foreach(var host in iHosts)
    {
        if (host.HostType == "Machine1")
        {// machine type 1
             task = CallRestartMachine1(host.IP);
        }
        else if (host.HostType == "Machine2")
        {// machine type 2
            task = CallRestartMachine2(host.IP);
        }

         // Add task to task list - for subsequent parallel processing
         tasks.Add(task);
    }


    // Run all tasks in task list in parallel
    await Task.WhenAll(tasks);
}

private static async Task CallRestartMachine1(string host)
{// helper method: reboot machines of type 1

    //RebootByWritingAFile is method that returns a Task, you need to await it
    // that is why the compiler is warning you
    await RebootByWritingAFile(host);

}

private static async Task CallRestartMachine2(string host)
{// helper method: reboot machines of type 2

    await RebootByNetwork(host);

}

关于c# - 如何异步调用静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52998866/

相关文章:

javascript - MVC Controller Action 返回 html 而不是 bool

c# - 设计帮助 - 对象修改并保存另一个对象

c# - 为 WPF 文本框实现验证

javascript - firefox 跟踪保护阻止 facebook js sdk 的异步加载

c# - 您是否需要后台 worker 或多个线程来触发多个异步 HttpWebRequest?

c# - 从 xml 文件中检索数据并插入到数据库表中

c - 避免共享对象中的内部线程

ios - Swift XCode 使用任务从网站提取数据,但我无法将数据获取到其他函数中以使用 TableView 显示它

c# - 如何修复 Task.Run 从 UI 线程抛出 STA 错误

c# - 何时使用 Task.Run 而不是