Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make TelegramBotClient disposable #845

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
35 changes: 34 additions & 1 deletion src/Telegram.Bot/TelegramBotClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ namespace Telegram.Bot
/// <summary>
/// A client to use the Telegram Bot API
/// </summary>
public class TelegramBotClient : ITelegramBotClient
public class TelegramBotClient : ITelegramBotClient, IDisposable
{
/// <inheritdoc/>
public int BotId { get; }
Expand Down Expand Up @@ -152,6 +152,8 @@ protected virtual void OnUpdateReceived(UpdateEventArgs e)

#endregion

#region Construction and disposal

/// <summary>
/// Create a new <see cref="TelegramBotClient"/> instance.
/// </summary>
Expand All @@ -176,6 +178,7 @@ public TelegramBotClient(string token, HttpClient httpClient = null)

_baseRequestUrl = $"{BaseUrl}{_token}/";
_httpClient = httpClient ?? new HttpClient();
_isCustomHttpClientUsed = httpClient != null;
}

/// <summary>
Expand Down Expand Up @@ -209,6 +212,36 @@ public TelegramBotClient(string token, IWebProxy webProxy)
_httpClient = new HttpClient(httpClientHander);
}

private bool _isDisposed;
private readonly bool _isCustomHttpClientUsed;

/// <summary>
/// Allows a <see cref="TelegramBotClient"/> to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.
/// </summary>
~TelegramBotClient() => dispose();

/// <summary>
/// Disposes this <see cref="TelegramBotClient"/>
/// </summary>
public void Dispose()
{
dispose();
GC.SuppressFinalize(this);
}

private void dispose()

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rename method in conformity with naming conventions

{
if (_isDisposed)
return;

if (!_isCustomHttpClientUsed)
_httpClient.Dispose();

_isDisposed = true;
}

#endregion

#region Helpers

/// <inheritdoc />
Expand Down