简体   繁体   中英

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.

Anyway, I'm writing a client in C# .Net that interacts with rtorrent via RPC. I'm storing the torrent client information in an ITorrentClient interface, and torrent information in a Torrent object. To get data about the torrent, it needs to call a function from ITorrentClient, for example:

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. 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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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