WPF应用程序DispatchTimer每两秒更新一次而不是一次

时间:2017-11-19 23:13:25

标签: c# wpf

我试图使用DispatcherTimer()每秒调用一个方法;这在更新计时器时工作正常,但是每当我尝试更新方法中的任何UI Emements时,计时器似乎每2秒而不是每秒都打勾,我添加到更新的UI元素越多,则会增加计时时间,窗口也不能在蜱虫之间被拖到屏幕周围。

我怎样才能有时间正确更新每一秒?

我正在查询网络API以接收数据。我想知道这可能是问题吗?

private void btnConnect_Click(object sender, RoutedEventArgs e)
{ 
    var dispatcherTimer = new DispatcherTimer();
    dispatcherTimer.Tick += new EventHandler(DispatcherTimer_Tick);
    dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
    dispatcherTimer.Start();
}        

private void DispatcherTimer_Tick(object sender, EventArgs e)
{            
    // Updating the Label which displays the current second
    lblTime.Content = DateTime.Now.ToString("HH:mm:ss");

    lblSizeBTC_USD.Content = "SIZE " + Api.GetProductTicker(productId).Result.size;            

    // Forcing the CommandManager to raise the RequerySuggested event
    CommandManager.InvalidateRequerySuggested();
}

调用web api的方法

public static async Task<ProductTicker> GetProductTicker(string productId)
{
    string ts = GetNonce();
    string method = "/products/" + productId + "/ticker";
    string sig = GetSignature(ts, "GET", method, string.Empty);
    ProductTicker productTicker;

    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(baseURL);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Add("CB-ACCESS-KEY", apiKey);
        client.DefaultRequestHeaders.Add("CB-ACCESS-SIGN", sig);
        client.DefaultRequestHeaders.Add("CB-ACCESS-TIMESTAMP", ts);
        client.DefaultRequestHeaders.Add("CB-ACCESS-PASSPHRASE", passphrase);
        client.DefaultRequestHeaders.Add("User-Agent", userAgent);
        HttpResponseMessage response = client.GetAsync(method).Result;
        response.EnsureSuccessStatusCode();

        string json = await response.Content.ReadAsStringAsync();
        productTicker = JsonConvert.DeserializeObject<ProductTicker>(json);
    }

    return productTicker;
}

1 个答案:

答案 0 :(得分:0)

Clemens确实是正确的,下面是工作更新的代码。解决方案是使DispatcherTimer_Tick方法异步并等待GetProductTicker调用:

private async void DispatcherTimer_Tick(object sender, EventArgs e)
{            
    // Updating the Label which displays the current second
    lblTime.Content = DateTime.Now.ToString("HH:mm:ss");

    var productTicker = await Api.GetProductTicker(productId);

    lblSizeBTC_USD.Content = "SIZE " + productTicker.size;        

    // Forcing the CommandManager to raise the RequerySuggested event
    CommandManager.InvalidateRequerySuggested();
}