我正在開發一個應用程序,需要每5秒檢查一次數據庫(使用查詢),當它發生時,GUI凍結約0.5秒並且它真的很煩人。我怎樣才能每5秒檢查一次數據庫而不是凍結C#中的gui? [已解決]
這是我的代碼,我使用「System.Windows.Forms.Timer」,但我可以改變它。
private void TimerBackground(Object myObject, EventArgs eventArgs)
{
// code to check from DataBase that takes about 0.5 sec and freezes the GUI
// Then it will display the result to a label in a form
}
void main(){
System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
myTimer.Tick += new EventHandler(TimerBackground);
myTimer.Interval = 5000;
myTimer.Start();
}
有沒有更好的方法來做到這一點?
編輯: 進出口使用一個簡單的查詢,如:
string credentials = "Server=127.0.0.1;port=3306;Database=test;Uid=root;password=root;";
MySqlConnection conn = null;
try
{
conn = new MySqlConnection(credentials);
MySqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT * FROM myTable;";
conn.Open();
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//...
}
}
catch { }
finally { if (conn != null)conn.Close(); }
[解決]
嗯,我正在讀的意見,我決定研究有關await
其解決我的問題。 我只是寫了我的 「定時器功能」(TimerBackground)內:
private async void TimerBackground(Object myObject, EventArgs eventArgs)
{
// This prevents the GUI from freezing.
await Task.Run(() =>
{
runQueryFunction();
});
}
您尚未顯示您的查詢代碼。 – Servy
'myTable'有多大?你真的需要'選擇*'嗎? – EJoshuaS
@EJoshuaS myTable只有一個字段。查詢不是問題,我認爲這是計時器。 – suffuko