我上课了 - 类骨架的核心如下: -
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";
}
-------------------------------------------------------
.......................................................
}
现在,我不希望这个类是静态的,而是希望它能够以更强大的方式采用更多的异步方法。
基本上,获取配置列表,但异步处理它们。
如何采用这种方法?
答案 0 :(得分:-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";
}
}