定时器在第二次迭代后不更新事件

时间:2012-05-29 11:32:54

标签: c# timer timeout

我正在使用计时器 -

static int count = 0;

private void button1_Click(object sender, EventArgs e)
    {
        // set time
        timer1.Interval = System.Convert.ToInt32(textBox2.Text) * 1000;
        // start timer
        timer1.Enabled = true;

        // set iterations
        count = System.Convert.ToInt32(textBox3.Text);

    }

蜱是 -

private void timer1_Tick_1(object sender, EventArgs e)
    {
        count--;
        if (count == 0)
        {
            timer1.Enabled = false;

        }
        listBox1.Items.Add(textBox1.Text + " : " + count.ToString());

        var status = textBox1.Text + " : " + count.ToString();
        }

当我将时间设置为每秒一次,并且计数为4时,我假设这将每秒运行一次,并重复4次。然而,一旦它重复三次事件,它就会崩溃。 列表框更新为 -

test : 3
test : 2
test : 1

错误是 -

The operation has timed out

我相信这可能是因为我在计时器内打了一个webrequest - “

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);
        request.Headers.Add("Authorization", authHeader);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        using (Stream stream = request.GetRequestStream())
        {
            byte[] content = ASCIIEncoding.ASCII.GetBytes(postBody);
            stream.Write(content, 0, content.Length);
        }
        WebResponse response = request.GetResponse();`

如何解决这个问题?进一步阅读表明,当对URL进行两次以上的调用时会出现此错误。

2 个答案:

答案 0 :(得分:0)

尝试使用timer1.Stop()代替timer1.Enabled = false;

if (count == 0)
{
   timer1.Stop();
}

答案 1 :(得分:0)

我必须添加 -

response.Close();

行后 -

WebResponse response = request.GetResponse();