异步调用WCF的方法需要小心的地方

本文介绍了如何通过正确管理WCF客户端对象来避免内存泄露问题,同时探讨了同步与异步调用的区别及异常处理策略。

直接使用下面的代码,由于client对象占用的资源没有被释放,会导致内存泄露
GetSimServiceReference.GetSimServiceClient client = new GetSimServiceReference.GetSimServiceClient()
client.computerSimAsync(DepartmentNo, FileID, F_intput.Length, ReadStringArrayFromStrings());
上面的问题,可以使用下面的方法来避免

                    using (GetSimServiceReference.GetSimServiceClient client = new GetSimServiceReference.GetSimServiceClient())
                    {
                        client.computerSimA(DepartmentNo, FileID, F_intput.Length, ReadStringArrayFromStrings());
                    }

但是如果使用异步调用的方式,会导致调用不到远程服务,并且没有任何异常提示,很是让人摸不到头脑

                    using (GetSimServiceReference.GetSimServiceClient client = new GetSimServiceReference.GetSimServiceClient())
                    {
                       client.computerSimAsync(DepartmentNo, FileID, F_intput.Length, ReadStringArrayFromStrings());
                    }

 

最后,采用了如下的代码:
                 

                    try
                    {
                        GetSimServiceReference.GetSimServiceClient client = new GetSimServiceReference.GetSimServiceClient();
                        client.computerSim(DepartmentNo, FileID, F_intput.Length, ReadStringArrayFromStrings());
                        if (client.State != CommunicationState.Faulted) client.Close();

                    }
                    catch (CommunicationObjectFaultedException cofe)
                    {
                        ShowException.SaveLogAsTXTInfoex("调用WCF服务失败,异常信息:" + cofe.Message);
                    }
                    catch (Exception ex)
                    {
                        ShowException.SaveLogAsTXTInfoex("调用WCF服务失败,异常信息:" + ex.Message+f_intput.FullName);
                    }

 

转载于:https://www.cnblogs.com/goxmpx/p/3314184.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值