首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >.NET CF WebService ObjectDisposedException

.NET CF WebService ObjectDisposedException
EN

Stack Overflow用户
提问于 2012-05-29 07:58:02
回答 1查看 1.6K关注 0票数 2

我正试图解决我的一个智能设备项目(WindowsMobile6.5上的.NET CF3.5)的问题。

代码试图不断地进行webservice调用,以获取一些数据并在表单中使用。在使用过程中,对于特定的情况是抛出一个ObjectDisposedException并导致应用程序崩溃。堆栈跟踪是

代码语言:javascript
复制
System.ObjectDisposedException was unhandled
 Message="ObjectDisposedException"
 ObjectName=""
 StackTrace:
      at System.Threading.Timer.throwIfDisposed()
      at System.Threading.Timer.Change(UInt32 dueTime, UInt32 period)
      at System.Threading.Timer.Change(Int32 dueTime, Int32 period)
      at System.Net.HttpWebRequest.startReadWriteTimer()
      at System.Net.HttpWebRequest.ConnectionClient.Read(Byte[] data, Int32 offset, Int32 length)
      at System.Net.HttpReadStream.NetworkRead(Byte[] data, Int32 offset, Int32 length)
      at System.Net.ChunkedReadStream.fillBuffer()
      at System.Net.ChunkedReadStream.getLine()
      at System.Net.ChunkedReadStream.doRead(Byte[] data, Int32 offset, Int32 length)
      at System.Net.HttpReadStream.ReadToDrain(Byte[] buffer, Int32 offset, Int32 length)
      at System.Net.HttpReadStream.doClose()
      at System.Net.HttpReadStream.Finalize()

我读过许多博客和论坛,包括这个,建议的解决方案似乎是在收到响应之前关闭请求流和请求。

代码语言:javascript
复制
requestStream = webRequest.GetRequestStream();
requestStream.Close(); // WE NEED THIS LINE in order to avoid the ObjectDisposedException.

但这对我的处境没有帮助。如果在将数据写入流之前关闭了requestStream,那么它不会做任何事情。如果我在收到响应后关闭,那么它会抛出InvalidOperationException。

以下是我的代码:

Reference.cs

代码语言:javascript
复制
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="ProductResolveServiceSOAP11Binding", Namespace="urn:ProductResolveService")]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(Exception))]
public partial class ProductResolveService : System.Web.Services.Protocols.SoapHttpClientProtocol {

    /// <remarks/>
    public ProductResolveService() {
        this.Url = "http://172.26.37.115:8080/axis/services/ProductResolveService";
    }

    /// <remarks/>
    [System.Web.Services.Protocols.SoapDocumentMethodAttribute("urn:getResolvedEpcs", RequestNamespace="http://services.axis.oatsystems.com", ResponseNamespace="http://services.axis.oatsystems.com", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
    [return: System.Xml.Serialization.XmlElementAttribute("return", IsNullable=true)]
    public ResolvedProductList getResolvedEpcs([System.Xml.Serialization.XmlElementAttribute(IsNullable=true)] EpcToResolve message) {
        object[] results = this.Invoke("getResolvedEpcs", new object[] {
                    message});
        return ((ResolvedProductList)(results[0]));
    }

    /// <remarks/>
    public System.IAsyncResult BegingetResolvedEpcs(EpcToResolve message, System.AsyncCallback callback, object asyncState) {
        return this.BeginInvoke("getResolvedEpcs", new object[] {
                    message}, callback, asyncState);
    }

    /// <remarks/>
    public ResolvedProductList EndgetResolvedEpcs(System.IAsyncResult asyncResult) {
        object[] results = this.EndInvoke(asyncResult);
        return ((ResolvedProductList)(results[0]));
    }
}

Form1.cs

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using System.Web.Services.Protocols;
using System.Windows.Forms;
using NFEHandlingProject.StatusService;
using System.IO;
using MVProductResolveService;


namespace NFEHandlingProject
{
    public partial class Form1 : Form
    {
        private Thread resolveThread;
        int counter = 0;

        public Form1()
        {
            InitializeComponent();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (resolveThread == null)
            {
                this.BeginInvoke((Action)delegate { lstbxStatusMsgs.Items.Add("Resolve Product: Creating Thread"); lstbxStatusMsgs.SelectedIndex = lstbxStatusMsgs.Items.Count - 1; });

                resolveThread = new Thread(new ThreadStart(GetEpcProductMapping));
                resolveThread.IsBackground = true;
                resolveThread.Priority = ThreadPriority.BelowNormal;

                resolveThread.Start();
            }
        }

        object syncRoot2 = new object();
        bool resolving = false;

        private void GetEpcProductMapping()
        {
            lock (syncRoot2)
            {
                if (resolving)
                {
                    return;
                }

                resolving = true;
            }

            while (resolving)
            {
                using (ProductResolveService2 productResolveService = new ProductResolveService2())
                {
                    EpcToResolve epcToResolve = null;

                    try
                    {
                        this.BeginInvoke((Action)delegate { lstbxStatusMsgs.Items.Add("Resolve Product: Resolving..."); lstbxStatusMsgs.SelectedIndex = lstbxStatusMsgs.Items.Count - 1; });

                        productResolveService.Url = "http://172.26.37.115:8080/axis/services/ProductResolveService?wsdl";

                        productResolveService.Timeout = 60000;

                        // The input object that is sent to xpress
                        epcToResolve = new EpcToResolve();

                        string epcBase = "3410402AEA0000000000";
                        int baseDec = Convert.ToInt32("1000", 16);

                        // Creating the input of epc's baed on the ResolveBatchSize and number epcs's that needs to be resolved at xpress
                        string[] epcs = new string[1];
                        for (int i = 0; i < 1; i++)
                        {
                            int epcDec = baseDec + i;
                            epcs[i] = epcBase + epcDec.ToString("X");
                        }

                        // setting the epc list which is the input that is sent to xpress
                        epcToResolve.epcList = epcs;

                        //pass the flag to check if say whether the productInformation or just the product_id is resolved
                        epcToResolve.returnOnlyProductId = false;

                        //return productResolveService.getResolvedEpcs(epcToResolve);
                        productResolveService.getResolvedEpcs(epcToResolve);
                        this.BeginInvoke((Action)delegate { lstbxStatusMsgs.Items.Add("Resolved"); lstbxStatusMsgs.SelectedIndex = lstbxStatusMsgs.Items.Count - 1; });
                    }
                    catch (SoapHeaderException)
                    {
                        // do nothing
                    }
                    catch (SoapException se)
                    {
                        this.BeginInvoke((Action)delegate { lstbxStatusMsgs.Items.Add("Problem resolving products at xpress"); lstbxStatusMsgs.SelectedIndex = lstbxStatusMsgs.Items.Count - 1; });
                    }
                    catch (WebException we)
                    {
                        // get the reason for the exception
                        WebExceptionStatus status = we.Status;
                        String description = we.Message;

                        WebResponse response = we.Response;
                        if (response != null)
                        {
                            Stream respStream = response.GetResponseStream();

                            if (respStream != null)
                            {
                                respStream.Close();
                                respStream.Dispose();
                                respStream = null;
                            }
                            // close the response
                            response.Close();
                            response = null;
                        }
                        // Case when there is no connectivity. Just display an error message to the user to indicate that there is no connectivity.
                        this.BeginInvoke((Action)delegate { lstbxStatusMsgs.Items.Add("Resolve Product: There is no connectivity to xpress"); lstbxStatusMsgs.SelectedIndex = lstbxStatusMsgs.Items.Count - 1; });
                    }
                    catch (ThreadAbortException)
                    {
                        // Do nothing. Do not log
                    }
                    catch (System.Exception e)
                    {
                        this.BeginInvoke((Action)delegate { lstbxStatusMsgs.Items.Add("An exception occured when fetching data from xpress"); lstbxStatusMsgs.SelectedIndex = lstbxStatusMsgs.Items.Count - 1; });
                    }

                    try
                    {
                        Thread.Sleep(200);
                    }
                    catch
                    {
                    }
                }
            }

            resolving = false;
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            if (resolveThread != null && resolving)
            {
                resolveThread.Abort();
                resolveThread.Join();
                resolveThread = null;
                resolving = false;

                this.BeginInvoke((Action)delegate { lstbxStatusMsgs.Items.Add("Resolve Product: Stopped Thread"); lstbxStatusMsgs.SelectedIndex = lstbxStatusMsgs.Items.Count - 1; });
            }
        }
    }
}

单击表单中的Start Button,线程将被创建,并继续调用webservice,当停止被调用时,线程将停止。重复启动和停止会导致ObjectDisposedException (这就是我复制这个异常的方式)。

在这方面的任何帮助都将受到高度赞赏,因为我几天来一直试图解决这一问题。

谢谢森希尔

EN

回答 1

Stack Overflow用户

发布于 2017-01-25 07:10:35

这是个很旧的职位。然而,我想在这里记录我的答案,以供任何仍在寻找答案的人使用。

有两种选择:

  1. 迁移到WCF客户端,这要简单得多,而且更干净。
  2. 使用以下解决方案。

公共类ExtendedDataImport : DataImport.DataImport {私有WebRequest webRequest;私有WebResponse webResponse;/此方法重写生成的方法并设置参数,以便使用HTTP1.0/(不进行分块)。如果保留默认参数,它/有时会失败。/受保护的覆盖WebRequest GetWebRequest(Uri uri) { webRequest = base.GetWebRequest(uri);(HttpWebRequest)WebRequest.KeepAlive= false;((HttpWebRequest)webRequest).ProtocolVersion = HttpVersion.Version10;){ if (webResponse != null) { Stream responseStream = webResponse.GetResponseStream();responseStream.Close();responseStream.Dispose();responseStream = null;webResponse.Close();webResponse = null;}如果(webRequest != null) { //中止WebRequest,清除try请求和//停止导致ObjectDisposedException try{webRequest.Abort()的计时器;webrequest = null;} catch (ObjectDisposedException ex) { //忽略在折叠链接//http://social.msdn.microsoft.com/Forums/en/netfxcompact/thread/8f21514c-9b7c-40d3-96c9-794c0dc167fe }}中提到的已释放的对象异常,保护的覆盖空洞处理(bool处理){ Close();base.Dispose(处理);} }

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10795185

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档