2

我正在制作一个简单的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首先在属性窗口中生成了方法。无论如何,它现在有效。感谢所有的帮助!

4

1 回答 1

4

如果在处理程序期间发生异常或操作被取消,则您的e.Result属性将为 null,但如果发生错误,获取它应该引发 a。RunWorkerCompletedDoWorkTargetInvocationException

检查e.Error是否有异常,并e.Cancelled检查是否取消。

在旁注中,我怀疑您的Timer对象实际上应该是Stopwatch. 该类Timer旨在安排事件运行,而不是测量时间。

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    var stopwatch = System.Diagnostics.Stopwatch.StartNew();
    TestObject obj = new TestObject();
    obj.Request = webResponse();
    stopwatch.Stop();
    obj.Time = stopwatch.Ellapsed.ToString();
    e.Result = obj;
}
于 2013-04-30T17:37:25.323 回答