如何停止计时器或使用相同的旧计时器来使用diff参数调用相同的URL?

时间:2014-05-13 06:10:20

标签: c# windows-phone-7 windows-phone-8 timer

我有问题,我使用计时器调用URL(此URL包含数字作为参数),并在第一次调用计时器工作正常然后我调用方法调用不同数字的URL --->计时器启动新计时器而不杀死旧计时器或使用它,我使用了timer.stop(),但这是停止一切。

我需要帮助如何制作,请帮助我。

这是我的计时器代码: -

public void GetOpentPos1(object sender,string accountID) 
{
    GetOpentPos(sender,accountID);
    DispatcherTimer newTimer = new DispatcherTimer();

    newTimer.Interval = TimeSpan.FromMilliseconds(2000);
    //newTimer.Tick += new EventHandler(GetOpentPos);
    newTimer.Tick += new EventHandler((sender1, e) => GetOpentPos(sender,accountID));

    newTimer.Start();

}


private void GetOpentPos (object sender,string accountID)
{
    var request = HttpWebRequest.Create(new Uri("http://x.x.x.x/vertexweb10/webservice.svc/GetOpenPositions?AccountId="+accountID)) as HttpWebRequest;

    request.Method = "GET";

    if (request.Headers == null)
    {
        request.Headers = new WebHeaderCollection();
    }
    // My code
}   

我打电话给第二个电话: -

GetOpentPos1(sender,accountID);

注意:

计时器应该继续工作,直到我再次打电话。

1 个答案:

答案 0 :(得分:0)

Thread.Sleep()效率极低。我通常不建议在生产解决方案中使用此方法。但是,它可能是最简单的解决方案。的

如果您只是想间隔调用一个函数,则不需要使用计时器。您需要使用Thread.Sleep()。你可以这样做。

public void GetOpentPos1(object sender,string accountID) 
{
    while (1) // loop forever
    {
        GetOpentPos(sender,accountID);
        Thread.Sleep(2000);
    }
}

private void GetOpentPos (object sender,string accountID)
{
    var request = HttpWebRequest.Create(new Uri("http://x.x.x.x/vertexweb10/webservice.svc/GetOpenPositions?AccountId="+accountID)) as HttpWebRequest;

    request.Method = "GET";

    if (request.Headers == null)
    {
        request.Headers = new WebHeaderCollection();
    }
// My code
} 

您可以在http://msdn.microsoft.com/en-us/library/d00bd51t(v=vs.110).aspx处获得Thread.Sleep的另一个示例。