我遇到了在C#代碼中實現計時器的問題。我正在做什麼的高級別概述,我有一個WPF應用程序,基於數據饋送每三秒更新顯示給用戶的數據。窗口上的大多數數據每三秒鐘發生一次更改,但我試圖爲count執行SQL查詢,而我只希望數據每5分鐘更新一次。所以我建立了如下所示的SQL查詢和下面顯示的計時器,但計時器希望它是一個無效的時候,它必須返回一個字符串,我不知道如何克服這一點。在C#代碼中遇到問題
我在使用定時器(運行在我的主法)原嘗試:
Timer t = new Timer(TimeSpan.FromMinutes(5).TotalMilliseconds); // set the time (5 min in this case)
t.AutoReset = true;
t.Elapsed += new System.Timers.ElapsedEventHandler(SQLDataTotalCalls());
t.Start();
我對SQL查詢方法:
public string SQLDataTotalCalls(object sender, ElapsedEventArgs a)
{
DateTime dte = DateTime.Today;
string fixedStartDate = String.Format("{0:yyyy-MM-dd " + "05:00:00.000" + "}", dte);
string fixedEndDate = String.Format("{0:yyyy-MM-dd " + "05:00:00.000" + "}", dte.AddDays(1));
SqlConnection connection = null;
try
{
var dataSet = new DataSet();
connection = new SqlConnection("Data Source=QL1OADB1;Initial Catalog=OADB;User Id=username;Password=password;
connection.Open();
var command = new SqlCommand("SELECT COUNT(SOURCEID) AS 'MYCOUNT' "
+ "FROM [OADB].[oadb].[CmsCallHistory] "
+ "WHERE disposition = 2 and DISPSPLIT in (" + SkillNumber + ") AND SEGSTOP BETWEEN '" + fixedStartDate + "' and '" + fixedEndDate + "'",
connection)
{
CommandType = CommandType.Text
};
var dataAdapter = new SqlDataAdapter { SelectCommand = command };
dataAdapter.Fill(dataSet);
return dataSet.Tables[0].Rows[0]["MYCOUNT"].ToString();
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
finally
{
if (connection != null)
{
connection.Close();
}
}
}
更新:
每建議的答案如下,我已經將上面的內容更改爲:
async Task RunPeriodicQueryTotalCalls()
{
TimeSpan interval = TimeSpan.FromMinutes(5);
while (true)
{
await Task.Delay(interval);
string result = await Task.Run(SQLDataTotalCalls);
TotalDailyCalls = result;
}
}
我已經更新了我的方法的SQL查詢有這樣的聲明:
public string SQLDataTotalCalls() { ... }
但我得到一個編譯器錯誤:
error CS0121: The call is ambiguous between the following methods or properties: 'Task.Run<TResult>(Func<TResult>)' and 'Task.Run(Func<Task>)'
你想用這個字符串做什麼? – Steve