添加对象后,后台工作结果对象为空

本文关键字:对象 结果 工作 后台 添加 | 更新日期: 2023-09-27 18:11:45

我正在制作一个简单的WinForms程序,应该从网站得到响应并测量处理所需的时间。

我不明白为什么e.Result是空后这样做:e.Result = obj;

我从MSDN网站得到了web请求代码,但我不确定它是否正确实现。

用于启动后台worker:

    private void button1_Click(object sender, EventArgs e)
    {
        backgroundWorker1.RunWorkerAsync();
    }
处理字符串的类:
    public class TestObject
    {
        public string Request { get; set; }
        public string Time { get; set; }
    }

DoWork方法:

    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;
    }

Web请求代码

    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;
    }

编辑:这是显示https://i.stack.imgur.com/kGsxO.jpg的错误我编辑了秒表部分。我认为backgroundWorker1.RunWorkerAsync();可能是问题所在。完成后,backgroundWorker1IsBusy参数为True。紧接着RunWorkerCompleted启动IsBusy为假

EDIT2:解决了,backgroundWorker1_DoWork没有在属性窗口的DoWork属性中输入。我不知道这是怎么发生的,我首先在属性窗口中生成了backgroundWorker1_DoWork方法。不管怎样,它现在起作用了。谢谢所有的帮助!

添加对象后,后台工作结果对象为空

如果在DoWork处理程序期间发生异常或如果操作被取消,则RunWorkerCompleted中的e.Result属性将为null,但如果发生错误,则抓取它应引发TargetInvocationException

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

顺便说一句,我怀疑你的Timer对象实际上应该是StopwatchTimer类用于调度要运行的事件,而不是测量计时。

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;
}