當我用F10按鈕逐步調試這個小程序時,程序是合理的,直到達到timer.Elapsed +=
的水平。在此之後,它應該去打電話給我的方法Check(MyConn)
,但它不!它回到MyConn.Close();
,它在這兩者之間反彈,然後突然關閉程序!C中的方法和計時器#
我想知道問題來自哪裏......可能是從這一行開始的:timer.Elapsed += (timerSender, timerEvent) => timer_Elapsed(timerSender, timerEvent, MyConn);
?這是一個解決方案張貼在這個論壇上,如果我想在參數MyConn
到timer_Elapsed
...
在此先感謝您的幫助!
static void Main(string[] args)
{
// create connection
string ConnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\mike\\Documents\\Database1.mdb;";
OleDbConnection MyConn = new OleDbConnection(ConnStr);
MyConn.Open();
initTimer(MyConn);
MyConn.Close();
}
static void initTimer(OleDbConnection MyConn)
{
//set up a timer
Timer timer = new Timer();
timer.Interval = 2000; // check every 2s (2000ms) if the values in the database changed
timer.Enabled = true; //enable the timer, so when the timer elapses after 2s, it performs some calculations
timer.Elapsed += (timerSender, timerEvent) => timer_Elapsed(timerSender, timerEvent, MyConn);
}
static void timer_Elapsed(object sender, ElapsedEventArgs e, OleDbConnection MyConn)
{
Check(MyConn); // Check is a method I have in my program which takes as argument "MyConn"
}
幾件事 - 什麼是例外? 'Check'用'MyConn'對象做什麼?因爲您在*之前立即關閉連接*計時器有機會使用它。 – James 2013-05-03 11:10:23