简体   繁体   中英

How to properly dispose third party object (TelegramBotClient) in C#

I am using TelegramBotClient component in my project. Unfortunately the component does not suggest any Dispose() method. In my project I need to renew the object based on the token provided:

public TelegramBotClient NewClient(string token)
        {
            return new TelegramBotClient(token);
        }

I need to dispose the object created

NewClient(token).SendTextMessageAsync(message.Chat.Id, message.Text, replyMarkup: keyboard, parseMode: Telegram.Bot.Types.Enums.ParseMode.Html);

How can I properly dispose the object?

If the third party-class implements IDisposable interface, then you can create object of that class with using block. This way the object disposal will be taken care by the framework.

If the class does not implements IDisposable that means that the class does not use any unmanaged resources and the author of the class does not see any possibility of memory leak caused by this class object if it not disposed intentionally.

If you still want to make sure that the third-party class object release the resources as soon at its usage is over, you can do that manually by wrapping it in your own class which implement IDisposable .

public class TextMessageClient : IDisposable
{
    bool disposed = false;
    private Telegram.Bot.TelegramBotClient client;

    public TextMessageClient()
    {
        //Write your own logic to get the token
        //Or accept the token as an argument of constructor.
        var token = Guid.NewGuid().ToString();
        client = new Telegram.Bot.TelegramBotClient(token);
    }

    public TextMessageClient(string token)
    {
        client = new Telegram.Bot.TelegramBotClient(token);
    }

    public async Task<Telegram.Bot.Types.Message> SendMessageAsync(string chatId, string message, string, IReplyMarkup keyboard, )
    {
        return await client.SendMessageAsync(chatId, message, replyMarkup: keyboard, parseMode: Telegram.Bot.Types.Enums.ParseMode.Html);
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    // Protected implementation of Dispose pattern.
    protected virtual void Dispose(bool disposing)
    {
        if (disposed)
            return;

        if (disposing)
        {
            client = null;
        }

        disposed = true;
    }
}

Now you can use this class as following.

using(var messageClient = new TextMessageClient())
{
    var message = await messageClient.SendMessageAsync(<somechatid>, <somemessage>, <somerelaymarkup>);
}

I hope this will help you resolve your issue.

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