【发布时间】:2018-01-02 23:37:23
【问题描述】:
在我的 UWP 项目中,我创建了一个按钮来启动 ThreadPoolTimer。它的周期为 45 秒。
我使用了以下代码:
public void Start_Click(Object sender,RoutedEventArgs e)
{
TimeSpan period = TimeSpan.FromSeconds(TIntervall);
ThreadPoolTimer PeriodicTimer = ThreadPoolTimer.CreatePeriodicTimer((source) =>
{
WriteDB();
Dispatcher.RunAsync(CoreDispatcherPriority.High,
() =>
{
});
},
period,
(source) =>
{
Dispatcher.RunAsync(CoreDispatcherPriority.High,
() =>
{
});
});
}
方法WriteDB()是一个同步函数,它连接到一个DB并插入一行;并在 Debug.WriteLine 中显示当前时间戳。
我的问题:显示的时间戳不是彼此相距 45 秒,而是在 1 到 40 秒之间。
为什么?我需要创建一些awaits 吗?
编辑(为 WriteDB() 添加代码):
private Boolean WriteDB()
{
string connectionString = "XXXXX";
Boolean ret = false;
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
string hum = "70";
string temp = "23";
string nnn = DateTime.Now.ToString();
string SetQuery = "INSERT INTO dbo.measure VALUES ('1'," + "N'" + nnn + "'" + "," + Convert.ToSingle(temp, new CultureInfo("en-US")) + "," + Convert.ToSingle(hum, new CultureInfo("en-US")) + ",N'TestDevice');";
System.Diagnostics.Debug.WriteLine("Query: " + SetQuery);
System.Diagnostics.Debug.WriteLine("Humidity at " + nnn + " = " + hum);
System.Diagnostics.Debug.WriteLine("Temperature: " + nnn + " = " + temp);
conn.Open();
if (conn.State == System.Data.ConnectionState.Open)
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = SetQuery;
int result = cmd.ExecuteNonQuery();
}
}
}
ret = true;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("Error: " + e.Message);
}
return ret;
}
【问题讨论】:
-
您的
TIntervall中有什么内容? -
TIntervall是const并且等于 45。 -
您能否发布
WriteDB()的代码以及显示时间戳的示例输出? -
我编辑了我的初始帖子并添加了所需的代码。
标签: c# uwp async-await