.Net 記憶體池

來源:互聯網
上載者:User

標籤:sys   free   read   情況   images   without   blank   lan   har   

  最近在開發 Pinpoint .Net 用戶端,和服務端通訊都是通過 TCP 或者 UDP,需要處理大量的 Byte 資料,使用 .Net Framework 只能通過 new Byte[] 的方式申請記憶體。用戶端每秒鐘處理的資料包非常多,通過這樣方式容易導致應用程式集區頻繁進行 GC。剛好在Microsoft官方的github看到開源的 .Net 記憶體池項目,特意分享一下。傳送門:https://github.com/Microsoft/Microsoft.IO.RecyclableMemoryStream

  記憶體池是在真正使用記憶體之前,先申請分配一定數量的、大小相等(一般情況下)的記憶體塊留作備用。當有新的記憶體需求時,就從記憶體池中分出一部分記憶體塊,若記憶體塊不夠再繼續申請新的記憶體。RecyclableMemoryStreamManager 內部定義了兩種類型的記憶體池,每種類型記憶體池的塊大小可以根據需要設定,可以設定記憶體池的上限。我們不需要關注記憶體的分配,像平常使用 MemoryStream 一樣調用 RecyclableMemoryStream 即可。

(引用:http://www.philosophicalgeek.com/2015/02/06/announcing-microsoft-io-recycablememorystream/)

  

  說明:(摘自項目README)

  • The semantics are close to the original System.IO.MemoryStream implementation, and is intended to be a drop-in replacement.
  • Rather than pooling the streams themselves, the underlying buffers are pooled. This allows you to use the simple Dispose pattern to release the buffers back to the pool, as well as detect invalid usage patterns (such as reusing a stream after it’s been disposed).
  • The MemoryManager is thread-safe (streams themselves are inherently NOT thread safe).
  • Each stream can be tagged with an identifying string that is used in logging - helpful when finding bugs and memory leaks relating to incorrect pool use.
  • Debug features like recording the call stack of the stream allocation to track down pool leaks
  • Maximum free pool size to handle spikes in usage without using too much memory.
  • Flexible and adjustable limits to the pooling algorithm.
  • Metrics tracking and events so that you can see the impact on the system.

  用法:

var sourceBuffer = new byte[]{0,1,2,3,4,5,6,7}; var manager = new RecyclableMemoryStreamManager(); using (var stream = manager.GetStream()) {     stream.Write(sourceBuffer, 0, sourceBuffer.Length); }

  

  注意:RecyclableMemoryStream 使用完,必須調用Dispose方法,不然無法將記憶體釋放回記憶體池,導致記憶體泄露!

.Net 記憶體池

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.