DBを5秒ごとに(照会で)チェックする必要があるアプリケーションを開発しています。そのとき、GUIは約0.5秒間フリーズしてしまい、本当に面倒です。どのように私は5秒ごとにdbをチェックすることができますし、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();
}
これを行うより良い方法はありますか?
EDITED: イムこのように、単純なクエリを使用して:
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(); }
[SOLVED]
さて、私はコメントを読んでいたと私は解決について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には1つのフィールドしかありません。クエリは問題ではない、私はそれがタイマーだと思う。 – suffuko