动态Web Service调用,解决内存回收基本问题...
2017-01-12 08:58
302 查看
原因:同步工具,需要实时调用第三方客户提供的接口进行解析,没有使用直接引用方式.考虑到方法后期会有变动,那样子得去更新引用.就用动态创建ws的代码(动态创建ws代码直接搜索出复制过来的.)).动态创建通过反射创建的代理对象,不能有效的释放内存(我的程序就是由于这原因导致内存每次请求都增加内存).所以使用了appdomian的方式进行程序隔离来请求ws,然后在卸载appdomian,来到达回收内存.(内存回收是基本达到了,但是程序的cpu使用率也上去了.暂时还找不出什么原因.)
这段代码加载ws接口,通过相关参数的传递获取接口的返回结果值(Result).
内存回收
#region 内存回收
//[DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
[DllImportAttribute("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize", ExactSpelling = true, CharSet = CharSet.Ansi, SetLastError = true)]
public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
/// <summary>
/// 释放内存
/// </summary>
public static void ClearMemory()
{
SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
}
#endregion
/// <summary> /// 动态调用WebService /// </summary> /// <param name="url">WebService地址</param> /// <param name="methodname">方法名(模块名)</param> /// <param name="args">参数列表</param> /// <returns>object</returns> public object InvokeWebService(string url, string methodname, object[] args) { try { return InvokeWebService(url, null, methodname, args); } catch (Exception) { throw; } } /// <summary> /// 动态调用WebService /// </summary> /// <param name="url">WebService地址</param> /// <param name="classname">类名</param> /// <param name="methodname">方法名(模块名)</param> /// <param name="args">参数列表</param> /// <returns>object</returns> private object InvokeWebService(string url, string classname, string methodname, object[] args) { try { string @namespace = "SyncTools.WebService.DynamicWebLoad"; if (classname == null || classname == "") { classname = GetClassName(url); } classname = @namespace + "." + classname; // Construct and initialize settings for a second AppDomain. AppDomainSetup appDomainSetup = new AppDomainSetup { ApplicationBase = System.Environment.CurrentDirectory, DisallowBindingRedirects = false, DisallowCodeDownload = false, ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile }; // Create the second AppDomain. // AppDomain appDomain = AppDomain.CreateDomain("SyncTools.WebService.DynamicWebLoad", null, appDomainSetup); AppDomain appDomain = AppDomain.CreateDomain("SyncTools.WebService.DynamicWebLoad"); Type t = typeof(ProxyObject); ProxyObject obj = (ProxyObject)appDomain.CreateInstanceAndUnwrap(t.Assembly.FullName, t.FullName); obj.LoadAssembly(url, @namespace); obj.Invoke(classname, methodname, args); var result = obj.Resutl; AppDomain.Unload(appDomain); appDomain = null; obj = null; return result; } catch (Exception) { throw; } finally { GC.Collect(); } } private string GetClassName(string url) { //URL为"http://localhost/InvokeService/Service1.asmx" //返回值为 Service1 string[] parts = url.Split('/'); string[] pps = parts[parts.Length - 1].Split('.'); return pps[0]; }
这段代码加载ws接口,通过相关参数的传递获取接口的返回结果值(Result).
internal class ProxyObject : MarshalByRefObject { Assembly assembly = null; private Object result = null; public Object Resutl { get { return this.result; } } public void LoadAssembly(string url, string @namespace) { // assembly = Assembly.LoadFile(@"TestDLL.dll"); //获取服务描述语言(WSDL) using (WebClient wc = new WebClient()) { using (Stream stream = wc.OpenRead(url + "?WSDL")) { ServiceDescription sd = ServiceDescription.Read(stream); ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); CodeNamespace cn = new CodeNamespace(@namespace); //生成客户端代理类代码 CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); CSharpCodeProvider csc = new CSharpCodeProvider(); ICodeCompiler icc = csc.CreateCompiler(); //设定编译器的参数 CompilerParameters cplist = new CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = false; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); //编译代理类 CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu); if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new StringBuilder(); foreach (CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } //生成代理实例,并调用方法 assembly = cr.CompiledAssembly; } } } public bool Invoke(string className, string methodName, params Object[] args) { if (assembly == null) return false; Type tp = assembly.GetType(className, true, true); if (tp == null) return false; MethodInfo method = tp.GetMethod(methodName); if (method == null) return false; Object obj = Activator.CreateInstance(tp); result = method.Invoke(obj, args); return true; }
内存回收
#region 内存回收
//[DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
[DllImportAttribute("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize", ExactSpelling = true, CharSet = CharSet.Ansi, SetLastError = true)]
public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
/// <summary>
/// 释放内存
/// </summary>
public static void ClearMemory()
{
SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
}
#endregion
相关文章推荐
- 动态调用Web Service及C#反射返回类或List对象问题解决
- 动态调用Web Service及C#反射返回类或List对象问题解决
- lucene大数据量的动态更新问题解决方式. 用内存
- 构建高性能ASP.NET站点 第七章 如何解决内存的问题(前篇)―托管资源优化―垃圾回收机制深度剖析
- 类型的已垃圾回收委托进行了回调。这可能会导致应用程序崩溃、损坏和数据丢失。向非托管代码传递委托时,托管应用程序必须让这些委托保持活动状态,直到确信不会再次调用它们的问题的解决方法
- 解决动态调用其他APK中的类so加载失败问题
- java动态加载指定的类或者jar包反射调用其方法-涉及其他jar中的类就报ClassNotFound问题分析及解决思路
- 解决pandas调用scipy时缺少动态运行库的问题
- java用jni调用dll动态库出现Can't find dependent libraries问题的解决方法
- 《对“XXX::Invoke”类型的已垃圾回收委托进行了回调。这可能会导致应用程序崩溃、损坏和数据丢失。向非托管代码传递委托时,托管应用程序必须让这些委托保持活动状态,直到确信不会再次调用它们》的问题的解决方法
- 遇到动态调用Parameters .AddWithValue()参数类型问题的解决方法
- 一个JS图片放大镜,实现动态记录的图片放大,避免内存泄露,解决IE6下无法遮盖select控件问题
- 类型的已垃圾回收委托进行了回调。这可能会导致应用程序崩溃、损坏和数据丢失。向非托管代码传递委托时,托管应用程序必须让这些委托保持活动状态,直到确信不会再次调用它们的问题的解决方法 续集
- AX中动态产生方法并且调用,解决根据不同条件产生不同SQL逻辑的问题很方便
- 【原创】构建高性能ASP.NET站点 第七章 如何解决内存的问题(前篇)—托管资源优化—垃圾回收机制深度剖析
- w7 下配置IIS ,出现的IIS 7.5 HTTP 错误 404.3 - Not Found解决办法及 调用32位动态库问题
- 关于动态页面在调用外部页面CSS样式IE6bug问题解决
- Object-C基础(10)——异常处理、反射、动态调用方法与内存回收
- 初学c++,释放动态数组内存出现的问题解决
- labview中,用相对路径动态调用的子VI,在生成EXE文件后无法调用问题的解决