Asynchronous programming is essential for building responsive applications, but it comes with challenges - particularly when you need to cancel operations.
Here's how to safely implement cancellation in C#.
The key to proper cancellation is the CancellationTokenSource class. This provides a token that can be passed to async methods and monitored for cancellation requests.
CancellationTokenSource
// Create a cancellation source with timeout var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); var token = cts.Token; try { // Pass token to async operations await DoLongRunningTaskAsync(token); } catch (OperationCanceledException) { // Handle cancellation gracefully Console.WriteLine("Operation was canceled"); } finally { // Always dispose the CancellationTokenSource cts.Dispose(); }
When writing cancellable async methods, check for cancellation at appropriate points:
async Task DoLongRunningTaskAsync(CancellationToken token) { // Check before starting expensive work token.ThrowIfCancellationRequested(); for (int i = 0; i < 100; i++) { // Periodically check during loops if (token.IsCancellationRequested) { // Clean up resources if needed CleanupResources(); // Then throw the standard exception throw new OperationCanceledException(token); } await Task.Delay(100, token); // Built-in methods accept tokens } }
token.ThrowIfCancellationRequested()
OperationCanceledException
By following these patterns, you can ensure your async operations respond promptly to cancellation requests while maintaining clean, resource-efficient code.
When working with SQL Server, you may often need to count the number of unique values in a specific column. This is useful for analyzing data, detecting duplicates, and understanding dataset distributions.
To count the number of unique values in a column, SQL Server provides the COUNT(DISTINCT column_name) function. Here’s a simple example:
COUNT(DISTINCT column_name)
SELECT COUNT(DISTINCT column_name) AS distinct_count FROM table_name;
This query will return the number of unique values in column_name.
column_name
If you need to count distinct combinations of multiple columns, you can use a subquery:
SELECT COUNT(*) AS distinct_count FROM (SELECT DISTINCT column1, column2 FROM table_name) AS subquery;
This approach ensures that only unique pairs of column1 and column2 are counted.
column1
column2
By leveraging COUNT(DISTINCT column_name), you can efficiently analyze your database and extract meaningful insights. Happy querying!
When working with URLs in C#, encoding is essential to ensure that special characters (like spaces, ?, &, and =) don’t break the URL structure. The recommended way to encode a string for a URL is by using Uri.EscapeDataString(), which converts unsafe characters into their percent-encoded equivalents.
string rawText = "hello world!"; string encodedText = Uri.EscapeDataString(rawText); Console.WriteLine(encodedText); // Output: hello%20world%21
This method encodes spaces as %20, making it ideal for query parameters.
For ASP.NET applications, you can also use HttpUtility.UrlEncode() (from System.Web), which encodes spaces as +:
using System.Web; string encodedText = HttpUtility.UrlEncode("hello world!"); Console.WriteLine(encodedText); // Output: hello+world%21
For .NET Core and later, Uri.EscapeDataString() is the preferred choice.
In C#, you can format an integer with commas (thousands separator) using ToString with a format specifier.
int number = 1234567; string formattedNumber = number.ToString("N0"); // "1,234,567" Console.WriteLine(formattedNumber);
Explanation:
"N0": The "N" format specifier stands for Number, and "0" means no decimal places. The output depends on the culture settings, so in regions where , is the decimal separator, you might get 1.234.567.
Alternative:
You can also specify culture explicitly if you need a specific format:
using System.Globalization; int number = 1234567; string formattedNumber = number.ToString("N0", CultureInfo.InvariantCulture); Console.WriteLine(formattedNumber); // "1,234,567"
Register for my free weekly newsletter.