简体   繁体   English

C#,程序设计,内存使用

[英]C#, Program Design, Memory Usage

So I'm pretty amateur at program design. 所以我在程序设计上非常业余。 I've done a few courses at uni but they all focus on learning the syntax and very basic design principles. 我在uni完成了一些课程,但它们都专注于学习语法和非常基本的设计原理。

Anyway, I'm writing a client in C# .Net that interacts with rtorrent via RPC. 无论如何,我正在用C#.Net编写一个客户端,该客户端通过RPC与rtorrent交互。 I'm storing the torrent client information in an ITorrentClient interface, and torrent information in a Torrent object. 我将torrent客户端信息存储在ITorrentClient界面中,并将torrent信息存储在Torrent对象中。 To get data about the torrent, it needs to call a function from ITorrentClient, for example: 要获取有关种子的数据,它需要从ITorrentClient调用一个函数,例如:

class Torrent
{
    string _hash;
    ITorrentClient _client;

    public Torrent(ITorrentClient client)
    {
        this._client = client;
    }

    public double UploadSpeed
    {
        get
        {
            return _client.getTorrentUploadSpeed(_hash);
        }
    }
}

Unfortunately this means that if you have a large amount of torrents in your torrent client (like I do), you're going to have hundreds of wasted ITorrentClients in memory. 不幸的是,这意味着,如果您的洪流客户端中有大量洪流(就像我一样),您将在内存中浪费数百个ITorrentClient。 How can I design my program so that I don't have hundreds of useless objects floating around? 如何设计程序,使周围没有数百个无用的对象?

Thanks! 谢谢!

If your implementation of ITorrentClient is a reference type (a class) and not a value type (a struct), the _client property of each Torrent will hold a reference to ITorrentClient , not the actual object . 如果您的ITorrentClient实现是引用类型(类)而不是值类型(结构),则每个Torrent_client属性将保存对ITorrentClient引用而不是对实际对象引用

Consider: 考虑:

var client = new MyTorrentClient(); // TorrentClient implements ITorrentClient
var t1 = new Torrent(client);
var t2 = new Torrent(client);

There's only one instance of MyTorrentClient in memory, and t1 and t2 hold a reference to it. 内存中只有MyTorrentClient的一个实例,并且t1t2拥有MyTorrentClient实例的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM