首页 > 其他分享 >Weak References in .NET

Weak References in .NET

时间:2023-06-16 14:35:22浏览次数:50  
标签:myweakerenceobject object Weak System References using new NET WeakReference

今天看到一个老外,用C#代码讲 WeakReferences的用法
不过我发现它的例子应该是用毛病的,在它的例子中weakRef应该没有逃开作用域,不能被正确回收,所以例子的结果也是不准的

末尾给出了我对其修改后的例子,给出了两种作用域的对比

Deciding When to Use Weak References in .NET

  Tapas Pal ByTapas Pal August 7, 2018  

.NET WeakReference Example

The .NET WeakReference Class represents a weak reference, which references an object while still allowing that object to be reclaimed by garbage collection. Now, let’s see an example. Create a console application from Visual Studio and name it MyWeakReference.

Create a WeakReference object and pass an object reference to the constructor call. In the following example, I have used the StringBuilder object.

static WeakReference myweakerenceobject;
myweakerenceobject = new WeakReference(new StringBuilder("My weak
   reference object."));

During execution, in the middle of the program, the garbage collector is executed by using GC.Collect. After this call, the object pointed to by the WeakReference no longer exists. After the call, I have checked if the object is still alive. Refer to the following code snippet.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyWeakReference
{
   class Program
   {
      static WeakReference myweakerenceobject;
      static void Main(string[] args)
      {
         myweakerenceobject = new WeakReference(new
            StringBuilder("My weak reference object."));
         if (myweakerenceobject.IsAlive)
         {
            Console.WriteLine((myweakerenceobject.Target as
               StringBuilder).ToString());
         }
         GC.Collect();
         // Check if still alive after GC call.
         if (myweakerenceobject.IsAlive)
         {
            Console.WriteLine("Object Alive");
         }
         Console.WriteLine("[I'm Done]");
         Console.Read();
      }
   }
}

The IsAlive property mentioned in the preceding code is an important property on the WeakReference type. This Boolean property indicates whether or not the object pointed to by the WeakReference has been collected.

I have also used the Target property in the code snippet. That returns an object that contains the reference to the instance I stored in the WeakReference. However, if the original object has already been garbage collected, the Target property will be null and then you can no longer reference the original object.

What Are the Differences Between Weak and Strong References?

The difference between a weak and a strong reference to an object is that, while the former still allows the garbage collector to reclaim the memory occupied by that object, a strong reference to an object doesn’t allow the garbage collector to reclaim the memory occupied by that object if the object is reachable.

Should We Use WeakReference?

A developer should use long weak references only when necessary because the object is unpredictable after finalization. We should avoid using weak references to small objects because the pointer itself may be as large or larger. Instead of weak references, we should develop an effective caching policy in an application.

WeakReference is often used for implementing Weak Events. Event handlers are a frequent cause of memory leaks, particularly when you have a long-lived service with events that multiple instances subscribe to.

Conclusion

That’s all for today. The following references are for for further study.

 

下面是我更改后的例子,可以看到,弱引用的target值已经不在被回收了


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyWeakReference
{
    class Program
    {
        ~Program()
        {
            Console.WriteLine("finalizer.");
        }
        
        static void Main(string[] args)
        {
            testStub();
            new Program().test(" normalMethod");
            GC.Collect();
            // Check if still alive after GC call.

            Console.WriteLine("[I'm Done]");
            Console.ReadKey();
        }

        static void testStub()
        {
            new Program().test(" static");
        }

        void test(string strFlag)
        {
            var str = new StringBuilder("My weak reference object.");
            WeakReference myweakerenceobject = new WeakReference(str, false);
            if (myweakerenceobject.IsAlive)
            {
                Console.WriteLine((myweakerenceobject.Target as
                   StringBuilder).ToString());
            }
            new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(delegate (object arg)
            {
                System.Threading.Thread.Sleep(2000);
                object[] weakArray = (arg as object[]);
                int iIndex = 0;
                foreach (WeakReference item in weakArray)
                {
                    if (item.IsAlive)
                    {
                        Console.WriteLine(
                            string.Format("iIndex:" + iIndex.ToString() + " Object Alive, value:{0}, flag:{1}", item.Target,  (weakArray[2] as WeakReference).Target
                            ));
                    }
                    else
                    {
                        Console.WriteLine("iIndex:" + iIndex.ToString() +" Object noAlive, flag:" + (weakArray[2] as WeakReference).Target);
                    }
                    iIndex++;
                }
                Console.WriteLine();
            })).Start(new object[] { new WeakReference(this), myweakerenceobject , new WeakReference(strFlag)});
            //str = null;
            //myweakerenceobject = null;
        }
    }
}

 

标签:myweakerenceobject,object,Weak,System,References,using,new,NET,WeakReference
From: https://www.cnblogs.com/ioriwellings/p/17485435.html

相关文章

  • .NET源码解读kestrel服务器及创建HttpContext对象流程
    .NET本身就是一个基于中间件(middleware)的框架,它通过一系列的中间件组件来处理HTTP请求和响应。因此,本篇文章主要描述从用户键入请求到服务器响应的大致流程,并深入探讨.NET通过kestrel将HTTP报文转换为HttpContext对象。通过本文,您可以了解以下内容:http的数据流转流程源码解读k......
  • 7. netstat
    作用:用于显示网络连接,路由表,接口状态。常用参数:netstat-a#显示所有连接中的Socketnetstat-n#用IP和端口号代替域名显示netstat-p#显示Socket对应的信息netstat-i#显示网卡信息列表netstat-r#显示路由表#常用组合:netstat-anp|more ......
  • 界面控件DevExpress v23.1.3全新首发——正式官宣支持.NET 7
    DevExpress拥有.NET开发需要的所有平台控件,包含600多个UI控件、报表平台、DevExpressDashboardeXpressApp框架、适用于VisualStudio的CodeRush等一系列辅助工具。屡获大奖的软件开发平台DevExpressv23.1已全新发布,该版本拥有众多新产品和数十个具有高影响力的功能,可为桌面、......
  • Kubernets 调度常用的命令-马哥教育
    taints内容包括key、value、effect:key就是配置的键值value就是内容effect是标记了这个taints行为是什么目前Kubernetes里面有三个taints行为:NoSchedule禁止新的Pod调度上来PreferNoSchedul尽量不调度到这台k8s的master节点本身就带有effect类型为NoSchedule的污......
  • 【Netty】「萌新入门」(二)剖析 EventLoop
    前言本篇博文是《从0到1学习Netty》中入门系列的第二篇博文,主要内容是介绍Netty中EventLoop的使用,优化及源码解析,往期系列文章请访问博主的Netty专栏,博文中的所有代码全部收集在博主的GitHub仓库中;概述事件循环对象EventLoop在Netty中,EventLoop是用于处理I/O事件的......
  • .Net6基础配置
    NET6App介绍.NET6的CoreApp框架,用来学习.NET6的一些变动和新特性,使用EFCore,等一系列组件的运用.。软件架构分为模型层,服务层,接口层来做测试使用0.如何使用IConfiguration、Environment直接在builder后的主机中使用。builder.Configuration;builder.Environment1.如何使......
  • 【.NET 深呼吸】全代码编写WPF程序
    学习Code总有这样一个过程:入门时候比较依赖设计器、标记语言等辅助工具;等到玩熟练了就会发现纯代码写UI其实更高效。而且,纯代码编写也是最灵活的。WindowsForms项目是肯定可以全代码编写的,哪怕你使用了设计器,它最后也是生成代码文件;而WPF就值得探索一下了。咱们知道,WPF使......
  • .net WebUploader 分块上传
    ​ 一、概述 所谓断点续传,其实只是指下载,也就是要从文件已经下载的地方开始继续下载。在以前版本的HTTP协议是不支持断点的,HTTP/1.1开始就支持了。一般断点下载时才用到Range和Content-Range实体头。HTTP协议本身不支持断点上传,需要自己实现。 二、Range  用于请求头......
  • .NET 文件上传服务设计
    .NET文件上传服务设计前言在b站学习了一个后端小项目,然后发现这个文件上传设计还挺不错,来实现讲解一下。项目结构如下:基于策略+工厂模式实现文件上传服务枚举在Model层创建即可publicenumUploadMode{Local=1,//本地上传Qiniu=2//七牛云......
  • c#.net WebUploader 分块上传
    ​ 以ASP.NETCoreWebAPI 作后端 API ,用 Vue 构建前端页面,用 Axios 从前端访问后端 API,包括文件的上传和下载。 准备文件上传的API #region 文件上传  可以带参数        [HttpPost("upload")]        publicJsonResultuploadProject(I......