【问题标题】:ThreadPoolTimer doesn't call method periodicallyThreadPoolTimer 不会定期调用方法
【发布时间】: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 中有什么内容?
  • TIntervallconst 并且等于 45。
  • 您能否发布WriteDB() 的代码以及显示时间戳的示例输出?
  • 我编辑了我的初始帖子并添加了所需的代码。

标签: c# uwp async-await


【解决方案1】:

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

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

【讨论】:

  • 是的。您可以将PeriodicTimer 设为类字段而不是局部变量,然后在创建新字段之前检查null
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-25
  • 2014-11-14
  • 1970-01-01
相关资源
最近更新 更多