“線程池”是可以用來在後臺執行多個任務的線程集合;
所謂線程池回調技術是指線程池中指定的線程定期執行指定的函數.
以下是用改技術獲取gps數據的例子:
using System.IO.Ports;
using System.Threading;
using com.ay.pda.device.gps;
using System.Runtime.InteropServices;
namespace com.ay.pda
{
public partial class GPSForm : Form
{
public System.Threading.Timer _gpggaTimer = null;
delegate void UpdateFormDelegate();
GPS gps = null;
public GPSForm(com.ay.pda.config config)
{
InitializeComponent();
gps = new GPS(gpsfilepath);
Cursor.Current = Cursors.Default;
}
public void GPSForm_Load(object sender, EventArgs e)
{
object threadName = "GPGGA";
TimerCallback tmrClbck = new TimerCallback(MethodInvok);//聲明線程回調委託
_gpggaTimer = new System.Threading.Timer(tmrClbck, threadName, 3000, -1);//實例化委託
}
private void MethodInvok(object threadName)
{
try
{
object gpsResult = new object();
if (_gpggaTimer != null)
gpsResult = this.Invoke(new com.ay.pda.device.gps.GPS.gpsDelegate(gps.initPosition), new object[] { _GPSTimes });
if (_gpggaTimer == null)
{
return;//該資源已經被釋放了
}
if (Convert.ToString(gpsResult) == "sucess")
{
this.Invoke(new UpdateFormDelegate(UpdateForm));
if (_gpsState)
{
_gpsState = false;
_gpggaTimer.Change(3000, -1); //如果現在已經獲的了GPS數據則3秒更新一次
}
else
_gpggaTimer.Change(4000, -1);
}
else
{
if (_gpsState)
{
_gpsState = false;
_gpggaTimer.Change(4000, -1); //如果現在已經獲的了GPS數據則3秒更新一次
}
else
_gpggaTimer.Change(5000, -1);
}
}
catch
{
return;
}
}
private void UpdateForm()
{
if (gps.getN() > 0)
{
textBoxYlat.Text = Convert.ToString(gps.getN());
main._PosY = Convert.ToString(gps.getN());
}
if (gps.getE() > 0)
{
textBoxXlong.Text = Convert.ToString(gps.getE());
main._PosX = Convert.ToString(gps.getE());
}
lab_time.Text = "時間:" + gps.getTime();
lab_height.Text = "海拔:" + gps.getHeight()+"米";
lab_speed.Text = "速度:" + Convert.ToString(gps.getSpeed())+"/公里";
lab_satellite.Text = "衛星:"+gps.getSatelliteCount()+"顆";
if (_gpsVoice )
{
PlaySound(config.getVoicePath("獲取GPS數據成功"), IntPtr.Zero, 0x0001 | 0x00020000);
_gpsVoice = false;
}
}