ThreadPoolTimer不会定期调用方法

时间:2018-01-02 13:24:59

标签: c# uwp async-await

在我的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秒之间。

为什么呢?我是否需要创建一些await

EDIT(为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;
}

1 个答案:

答案 0 :(得分:0)

唉......我找到了我的问题(相当愚蠢)的原因: 我在按钮上多次点击...

是不是每次点击都会启动一个带有自己的计时器的专用线程?