我有传感器详细信息列表,我需要为每个传感器获取配置并应用一些业务逻辑。我想做Aynchrosnously,就像每个传感器将调用相同的方法并同时执行其逻辑。我尝试使用Async并等待以下是示例。请告诉我,如果以下内容有助于执行每个传感器异步执行。
public static async Task GetSensor()
{
List<SensorMaster> sensorAddress = GetSensorService();
foreach (SensorMaster sensorInfo in sensorAddress)
{
await ParseSensor(sensorInfo);
}
}
private static async Task ParseSensor(SensorMaster senInfo)
{
List<Sensor> sTestdownTime = await GetTestDownTime(senInfo);
if (DateTime.Parse(sTestdownTime[0].LastHeartBeatAt.ToString()).Year > 1900)
{
CreateEvent(senInfo, sTestdownTime);
}
}
public static async Task<List<Sensor>> GetTestDownTime(SensorMaster senInfo)
{
List<Sensor> lstSensor = new List<Sensor>();
var connectionString = "Data Source=xxxx;Initial Catalog=xx;persist security info=True;User ID=xx;Password=xxx;";
var asyncConnectionString = new SqlConnectionStringBuilder(connectionString) { AsynchronousProcessing = true }.ToString();
using (var cn = new SqlConnection(asyncConnectionString))
{
cn.Open();
SqlCommand cmd = new SqlCommand("SetingSp", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@StationType", senInfo.SensorName));
cmd.Parameters.Add(new SqlParameter("@ThresholdValue", senInfo.SensorThreshold));
using (SqlDataReader dr = await cmd.ExecuteReaderAsync())
{
if (dr.HasRows)
{
while (dr.Read())
{
Sensor cpData = new Sensor();
cpData.SensorName = dr["SensorName"].ToString();
cpData.LastHeartBeatAt = Convert.ToDateTime(dr["LastTimeStamp"]);
lstSensor.Add(cpData);
}
}
}
return lstSensor;
}
}
答案 0 :(得分:0)
是的,它们将异步执行。但不是平行的。除非你有一个非常明显的性能问题,否则我认为你甚至不应该试图让它并行。
并行(例如Parallel.ForEach()
)将同时打开许多SqlConnections。不清楚你正在运行什么样的系统,以及预期的结果。