我有一个必须每五分钟运行一次的方法:
public float enConsumption()
{
while (true)
{
enValue = energyConsumtion(enValue);
Thread.Sleep(300000);
Console.WriteLine("Consumation **** ENVALUE" + Convert.ToString(enValue));
return enValue;
}
}
另外,我有一个含有12个元素的氧气图。我需要每2小时传递一个float数组,数组的每个元素的值是enConsumption()的数量。因此,我写了这个函数,函数控制时间,如果是在正确的时间间隔内,那么它会更新tempList数组:
public float[] passEnergyConsumptionToGarph()
{
if(compareTime(curruntTime,0,2)){
tempList[0] = enConsumption();
}
if (compareTime(curruntTime, 2, 4))
{
tempList[1] = enConsumption();
}
if (compareTime(curruntTime, 4, 6))
{
tempList[2] = enConsumption();
}
if (compareTime(curruntTime, 6, 8))
{
tempList[3] = enConsumption();
}
if (compareTime(curruntTime, 8, 10))
{
tempList[4] = enConsumption();
}
if (compareTime(curruntTime, 10, 12))
{
tempList[5] = enConsumption();
}
if (compareTime(curruntTime, 12, 14))
{
tempList[6] = enConsumption();
}
if (compareTime(curruntTime, 14, 16))
{
tempList[7] = enConsumption();
}
if (compareTime(curruntTime, 16, 18))
{
tempList[8] = enConsumption();
}
if (compareTime(curruntTime, 18, 20))
{
tempList[9] = enConsumption();
}
if (compareTime(curruntTime, 20, 22))
{
tempList[10] = enConsumption();
}
if (compareTime(curruntTime, 22, 24))
{
tempList[11] = enConsumption();
}
return tempList;
}
最后,我必须在我的主要活动中调用passEnergyConsumptionToGarph(),以便将其结果传递给我的oxyplot图。
因此我需要在后台运行enConsumption,我需要在用户点击按钮显示图的情况下调用passEnergyConsumptionToGarph()。我是.net的新手,我需要知道在这种情况下如何使用async和await。如果你指导我,我会很感激的。
已更新
考虑到收到的回复,我使用了一个计时器,以便每5分钟运行一次enConsumption()方法:
public void timerClass(){
var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromMinutes(5);
var timer = new System.Threading.Timer((e) =>
{
enConsumption();
}, null, startTimeSpan, periodTimeSpan);
}