.NET弱引用

來源:互聯網
上載者:User

      當把一個對象引用分配給一個變數時,該變數就包含對對象的一個強引用(strong reference)。垃圾收集器不會收回強引用仍在使用的對象。只要當變數離開範圍,或者顯示地給變數分配null時,強引用才被刪除。

      弱引用(weak reference)可以保持對對象的引用,同時允許垃圾收集器在它認為適當的垃圾收集時間釋放對象,回收記憶體。假設有一個對象建立相對便宜,但需耗費大量的記憶體,如果希望保持這個對象,在應用程式需要使用它,但也希望能夠告訴垃圾收集器,在必要時把記憶體收回。

      弱引用可以通過WeakReference類引用。

      在下面的執行個體代碼中,在ASP.NET應用程式開始時建立了一個32KB的字串,把字串分配給一個WeakReference執行個體,並把弱引用放在Application對象中供以後檢索。在Application_Start中的bigString變數離開範圍後,將不存在對字串執行個體的強引用。

        void Application_Start(object sender, EventArgs e)        {            String bigString = new String('A', 32768);            WeakReference weakRef = new WeakReference(bigString);            Application.Add("BigString",weakRef);        }

 

      如果能在垃圾收集發生之前訪問Application對象檢索字串,WeakReference對象的Target屬性將包含對字串的一個對象引用。如果Target屬性為空白,被弱引用的對象就已經被執行垃圾收集了。要使用就要重新建立這個字串。否則,可以提取Target屬性並用bigString變數建立一個強引用,然後在應用程式的開始處使用所建立的字串對象。

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                GetBigString();
        }

        private void GetBigString()
        {
            WeakReference weakReference;

            if (Application["BigString"] != null)
            {
                weakReference = Application["BigString"] as WeakReference;

                String bigString;
                bigString = weakReference.Target as String;

                if (bigString != null)
                    lbMessage.Text = "BigString retrieved from WeakReference";
                else
                    lbMessage.Text = "BigString was garbage collected";

            }
            else
                lbMessage.Text = "Unable to retrieved BigString From Application";
        }

        protected void btnGC_Click(object sender, EventArgs e)
        {
            GC.Collect();
            GetBigString();
        }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.