由于对象的状态,操作无效

时间:2015-02-26 13:28:47

标签: c# windows-phone-8.1 webclient

当快速连续发出多个请求时,我有时会遇到InvalidOperationException,由于对象的状态,该操作被标记为操作无效。我不完全确定以下代码有什么问题:

   this.Abort();

        this.request = (HttpWebRequest)WebRequest.Create(uri);

        this.result = new WebClientAsyncResult(this.request);

        if (data != null)
        {
            this.request.ContentType = "application/x-www-form-urlencoded";
            this.request.Method = "POST";
        }

        // BeginGetResponse does have a synchronous component
        // See: http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetresponse.aspx
        Action asyncAction = () =>
        {
            try
            {
                if (this.request == null)
                {
                    Debug.WriteLine("Request is null");
                    return;
                }

                if (request.Method == "POST")
                {
                    GetRequest(result, data, responseAction, errorAction);
                }
                else
                {
                    GetResponse(result, responseAction, errorAction);
                }
            }
            catch (InvalidOperationException ex)
            {
                Debug.WriteLine("Invalid");
                if (this.request == null)
                {
                    errorAction(new Error(ex.InnerException) {WasAborted = true});
                }
            }
        };

        Dispatcher.BeginInvoke(asyncAction, null, null);

        return this.result;

1 个答案:

答案 0 :(得分:1)

这是通过在lambda之外使用局部变量来解决的,因为它不会捕获字段的值,直到执行导致问题。