我正在制作一个简单的WinForms
程序,该程序应该从网站获得响应并测量处理所需的时间。
我不明白为什么e.Result
这样做后为空:e.Result = obj;
我从 MSDN 站点获得了 Web 请求代码,但我不确定它是否正确实施。
这是用于启动后台工作人员:
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
处理字符串的类:
public class TestObject
{
public string Request { get; set; }
public string Time { get; set; }
}
做工方法:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
TestObject obj = new TestObject();
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
obj.Request = webResponse();
stopwatch.Stop();
obj.Time = stopwatch.Elapsed.ToString();
e.Result = obj;
}
RunWorkerCompleted 方法:
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
TestObject test = e.Result as TestObject;
label1.Text = test.Request + test.Time;
}
网络请求代码
private string webResponse()
{
// Create a request for the URL.
WebRequest request = WebRequest.Create("http://www.tvz.hr");
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Display the status.
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
编辑:这是显示的错误http://i.imgur.com/Sb5BDFe.jpg
我已经编辑了秒表部分。我认为这backgroundWorker1.RunWorkerAsync();
可能是问题所在。完成后,IsBusy
参数backgroundWorker1
为True。并且在RunWorkerCompleted
开始之后立即IsBusy
是 False
EDIT2:已解决,backgroundWorker1_DoWork
未在“属性”窗口的 DoWork 属性中键入。我不知道这是怎么发生的,我backgroundWorker1_DoWork
首先在属性窗口中生成了方法。无论如何,它现在有效。感谢所有的帮助!