我创建了一个wpf应用程序,它控制一个标签和两个用于启动和停止计时器的按钮。
我创建了两个DispatcherTimers,一个计时器将在每50毫秒后触发一次,并用计数值更新标签。另一个DispatcherTimer将在每2秒后触发一次,它将数据发布到名为“http://posttestserver.com/post.php?dir=Test”的HTTP后测试服务器。在这个计时器中,我使用GetRequestStream,导致UI停止1秒但我的数据发布到posttestserver。 我使用了以下代码。
public partial class MainWindow:Window {
static int count = 0;
DispatcherTimer dispatchtimer = null;
DispatcherTimer WebDispatchTimer = null;
public MainWindow()
{
InitializeComponent();
dispatchtimer = new DispatcherTimer();
WebDispatchTimer = new DispatcherTimer();
WebDispatchTimer.Interval = TimeSpan.FromMilliseconds(2000);
dispatchtimer.Interval = TimeSpan.FromMilliseconds(50);
dispatchtimer.Tick += new EventHandler(dispatchtimer_Tick);
WebDispatchTimer.Tick += new EventHandler(senddata_Tick);
}
private void button1_Click(object sender, RoutedEventArgs e)
{
WebDispatchTimer.Start();
dispatchtimer.Start();
}
private void dispatchtimer_Tick(Object sender, EventArgs args)
{
count += 1;
label1.Content = count.ToString();
}
private void senddata_Tick(Object sender, EventArgs args)
{
string postdata = "This is a test that posts this string to a Web server\n";
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://posttestserver.com/post.php?dir=abcd");
request.Method = "POST";
request.ProtocolVersion = HttpVersion.Version11;
byte[] byteArray = Encoding.UTF8.GetBytes(postdata);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
request.Proxy = null;
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Flush();
dataStream.Close();
}
var response = request.GetResponse() as HttpWebResponse;
response.Close();
request.Abort();
request = null;
}
catch (WebException ex)
{
MessageBox.Show(ex.Message);
WebDispatchTimer.Stop();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
WebDispatchTimer.Stop();
}
}
private void button2_Click(object sender, RoutedEventArgs e)
{
WebDispatchTimer.Stop();
dispatchtimer.Stop();
}
}
我不希望我的UI挂起1秒钟。哪里弄错了?帮助我。