2015-04-01 61 views
-2

我有类---类框架的核心是在下面给出: -静态类转换成异步模式

class Pingdom 
     { 
      public static string Pingdom(List<Config> configtypes) 
      { 
       StringBuilder response = new StringBuilder(); 
       bool status = false; 
       foreach(var c in configtypes) 
       { 
        switch(c.Type) 
        { 
         case ConfigTypes.Database: 
          { 
           status = PingdomDB(c.ConnectionType); 
          } 
          break; 
         case ConfigTypes.API: 
          { 
           status = PingdomAPI(c.Endpoint); 
          } 
          break; 
        } 
       } 

       if (status) 
        return "Ping"; 
       else 
        return "No Ping"; 
      } 
------------------------------------------------------- 
....................................................... 
} 

现在,而不是类是静态的,我想它是在这样我可以以更强大的方式采用更多异步方法。

实质上,获取配置列表,但异步处理它们。

如何去做这个方法?

+1

这一切都取决于'PingdomDB'和'PingdomAPI',您需要向我们展示你的这些功能在做什么,我们就如何将其转化为被异步调用的任何建议。现在你的代码只返回列表中最后一个项目的状态,这是你真正想要的吗? – 2015-04-01 23:22:43

回答

-1
class Pingdom { 
     public static string PingMe(List<Config> configtypes) 
     { 
      bool status = true; 
      List<Task> tasks2 = new List<Task>(); 
      foreach (Config config in configtypes) 
      { 
       if (config.Type == ConfigTypes.Database) 
       { 
        tasks2.Add(Task.Factory.StartNew(() => { status = status && PingdomDB(config.ConnectionType); }, TaskCreationOptions.LongRunning)); 
       } 
       else if (config.Type == ConfigTypes.API) 
       { 
        tasks2.Add(Task.Factory.StartNew(() => { status = status && PingdomAPI(config.ConnectionType); }, TaskCreationOptions.LongRunning)); 
       } 
      } 
      Task.WaitAll(tasks2.ToArray(), System.Threading.Timeout.Infinite); 
      if (status) 
       return "Ping"; 
      else 
       return "No Ping"; 
     } 
    } 
+0

如果这些是长时间运行的任务,那么它将始终返回“Ping”。 您应等待任务完成或返回任务结果的状态。 由于每次对PingMe的调用都只创建1个任务,因此不需要列表。 – shr 2015-04-02 07:40:43

+0

对不起,刚才看到创建了多个任务。您仍然需要等待它们完成以计算状态的返回值。 var tasks2 =新列表>(); ...... //在foreach循环之后 等待Task.WhenAll(tasks2); tasks2.ForEach(t => status = status && t.Result); 返回状态? “平”:“不平”; – shr 2015-04-02 08:00:13

+0

谢谢,斯科特,我标记了它。谢谢,在我转移代码时,我忘了包含WaitAll。诅咒我的ADHD :) – 2015-04-02 16:55:41