我正在使用计时器 -
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
我相信这可能是因为我在计时器滴答声中发出网络请求 - '
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 次以上的调用时,会出现此错误。
尝试timer1.Stop()
而不是timer1.Enabled = false;
if (count == 0)
{
timer1.Stop();
}
我不得不添加 -
response.Close();
行后 -
WebResponse response = request.GetResponse();