到目前爲止,我對C#不是很熟悉,至少在選擇第一次使用某些方法時沒有足夠的自信。用於數據庫循環輪詢的C#計時器
什麼可能是最好的方式來組織基於SQL Server數據庫計時器的輪詢從我的WPF應用程序的控件更新?
請您分享一些關於這個問題的想法,或者可能的代碼示例如何實現?在多大程度上可能(或合理)進行這種投票的時間?什麼可能是危險的?
也許有一個標準和正確的方法來做到這一點?
到目前爲止,我對C#不是很熟悉,至少在選擇第一次使用某些方法時沒有足夠的自信。用於數據庫循環輪詢的C#計時器
什麼可能是最好的方式來組織基於SQL Server數據庫計時器的輪詢從我的WPF應用程序的控件更新?
請您分享一些關於這個問題的想法,或者可能的代碼示例如何實現?在多大程度上可能(或合理)進行這種投票的時間?什麼可能是危險的?
也許有一個標準和正確的方法來做到這一點?
如果你需要一個應用範圍的更新,並且它不會造成太大的延遲做了更新,最好的選擇是開始一個背景Thread
,可以運行和後期事件給用戶的數據已經刷新(可能首先通過向事件添加自定義EventArgs
來檢查是否已使用某些特定的邏輯進行了更改)。
例如,創建這個類的地方頂層的一個實例(也許你的主要形式的代碼):
using System;
using System.Threading;
using System.Windows.Forms;
public class PollerThread
{
private Thread _thread;
private SynchronizationContext _syncContext;
public event EventHandler UpdateFinished;
public PollerThread()
{
_syncContext = WindowsFormsSynchronizationContext.Current;
ThreadStart threadStart = new ThreadStart(ThreadStartMethod);
_thread = new Thread(threadStart);
_thread.Name = "UpdateThread";
_thread.IsBackground = true;
_thread.Priority = System.Threading.ThreadPriority.Normal;
}
public void Start()
{
if ((_thread.ThreadState & ThreadState.Unstarted) == ThreadState.Unstarted)
_thread.Start();
else
throw new Exception("Thread has already been started and may have completed already.");
}
public void ThreadStartMethod()
{
try
{
while (true)
{
// Go get the new data from the SQL server
OnUpdateFinished(); // Notify all subscribers (on their own threads)
Thread.Sleep(10000); // 10 sec wait before the next update
}
}
catch (ThreadAbortException)
{
// The thread was aborted... ignore this exception if it's safe to do so
}
}
protected virtual void OnUpdateFinished()
{
if (UpdateFinished != null)
{
SendOrPostCallback method = new SendOrPostCallback(
delegate(object state)
{
UpdateFinished(this, EventArgs.Empty);
});
_syncContext.Send(method, null);
}
}
}
訂閱每個需要以新的更新迴應UpdateFinished
事件的地區。這將在用於構建PollerThread
類的線程上執行。
這個答案可能聽起來有些鬆散,並且更具體地應用於Windows窗體項目,但實用性取決於您當前的實現。無論如何,至少你可以建立在這個基礎上。希望它有助於:)
您可以使用一個SqlDependency對象,儘管它將SQL Server 2005+與您的實現緊密聯繫在一起。
你的要求很一般描述,所以我只能在概括迴應:
一般:
十個客戶不是很多,一萬個是。十行很小,一千行變得又大又慢。回答這些問題將幫助您瞭解如何設置輪詢頻率。
您需要平衡其他考慮因素,如UI響應(異步執行數據更新),需要新數據以及知道數據庫更新的頻率,以確定最有效和最有效的設計。
昨晚我發現我忘了在這裏提到的東西。當他們被關閉時,不要忘記*取消分配窗體的事件監聽器,例如:'myPollerThread.UpdateFinished - = new EventHandler(myPollerThread_UpdateFinished);'否則關閉的窗體仍然會接收事件並且很可能會導致一些關於窗體的異常被處置。 – Codesleuth 2010-01-12 09:26:46