程式設計(控制器設計) switch-case 應用
程式設計(控制器設計) switch-case 應用
01.定時 執行/控制 switch-case & Timer(thread) -ChatGPT(C# switch case timer) [C# Console Timer]
using System;
using System.Timers;
class Program
{
static void Main(string[] args)
{
// 创建定时器
Timer timer = new Timer(1000); // 每秒执行一次
// 定时器事件
timer.Elapsed += (sender, e) =>
{
// 获取当前时间
DateTime now = DateTime.Now;
// 根据当前时间判断执行的操作
switch (now.Second)
{
case 0:
Console.WriteLine("整点报时:{0}点整", now.Hour);
break;
case 30:
Console.WriteLine("半点报时:{0}点半", now.Hour);
break;
default:
Console.WriteLine("当前时间:{0}:{1}:{2}", now.Hour, now.Minute, now.Second);
break;
}
};
// 启动定时器
timer.Start();
// 等待用户输入
Console.ReadLine();
}
}
02.順序/狀態機 控制 switch-case & Timer(thread)
using System;
using System.Timers;
class Program
{
public static int Step=0;
static void Main(string[] args)
{
// 创建定时器
Timer timer = new Timer(1000); // 每秒执行一次
Step=0;
// 定时器事件
timer.Elapsed += (sender, e) =>
{
// 根据当前时间判断执行的操作
switch (Step)
{
case 0:
Console.WriteLine("Step 0");
Step=1;
break;
case 2:
Console.WriteLine("Step 2");
Step=10;
break;
case 1:
Console.WriteLine("Step 1");
Step=2;
break;
default:
Step=0;
break;
}
};
// 启动定时器
timer.Start();
// 等待用户输入
Console.ReadLine();
}
}
03.switch函式不加break的效果 等同 if判斷式中執行 || 運算
int i=10
switch(i)
{
case 10:
case 20:
break;
}
//----
if((i==10) || (i==20))
{
}
04.簡化 多個if-else
int i=0;
if(i==0)
{
}
else if(i==1)
{
}
else if(i==2)
{
}
else
{
}
//---
switch(i)
{
case 0:
break;
case 1:
break;
case 2:
break;
}
3 thoughts on “程式設計(控制器設計) switch-case 應用”
使用 if 判斷式 定時 執行/控制
public class SyncThread//背景同步(上傳)資料到 cloud
{
private static int m_intStepCount = 0;
private static int m_intWaitCount = 0;//等待存取DB計數器
public static bool m_blnWait = false;//預防同時存取DB旗標
public static bool m_blnRunLoop = false;//執行序執行與否狀態變數
public static void ThreadMain()//執行序的主函數
{
m_blnRunLoop = true;
do
{
m_intStepCount++;
if (m_blnWait)
{
m_intWaitCount++;
if (m_intWaitCount >= 5)
{
m_blnWait = false;
m_intWaitCount = 0;
}
}
if (!HttpsFun.WebRequestTest(ref main.m_intNetworkLevel))//確認網路狀態
{
continue;
}
if (VTEAMCloudAPI.Authentication())
{
GetVTSTOREData();//每秒都執行一次
if (m_intStepCount % 2 == 0)//2秒執行一次
{
}//2秒執行一次
if (m_intStepCount % 3 == 0)//3秒執行一次
{
}//3秒執行一次
if (m_intStepCount % 4 == 0)//4秒執行一次
{
}//4秒執行一次
if (m_intStepCount % 5 == 0)//5秒執行一次
{
UploadData2Cloud();
m_intStepCount = 0;//清宮旗標,重新計數
}//5秒執行一次
}//if (VTEAMCloudAPI.Authentication())
Thread.Sleep(1000);//每次執行中間間隔時間
} while (m_blnRunLoop);
}//public static void mainSync()
規則: 最大週期為10秒 其中 每2秒要執行A動作一次 每3秒要執行B動作一次 每10秒要執行C動作一次
switch模式
switch(count)
{
case 02:
case 04:
case 06:
case 08:
case 10:
A();
if(count==10)
{
C();
}
break;
case 03:
case 06:
case 09:
B();
break;
}
count++;
if(count>10)
{
count=1;
}
sleep(1000);
if模式:
if((count==2)||(count==4)||(count==6)||(count==8)||(count==10))
{
A();
if(count==10)
{
C();
}
}
if((count==3)||(count==6)||(count==9))
{
B();
}
count++;
if(count>10)
{
count=1;
}
sleep(1000);
控制系統中大時間週期內 有包含數個重複性小時間任務要重複執行時
switch 語法 並不會比 if-else 更精簡/好維護