Grow with us: Join Postmark's new referral partner program and start earning
x

Official .NET Library Async/Await Examples

Async + Await are great additions to the .NET runtime, but we have seen some cases where async methods end up blocking in different contexts.

In the case of ASP.net, the SynchronizationContext may have strange behaviors that can cause postmark-dotnet calls to "block". Below are a couple examples to help illustrate how to use Async + Await with the official .NET library for Postmark.

Console example

using System;
using System.Threading.Tasks;
using PostmarkDotNet;

namespace PostmarkExamples {
    class Program {
        static void Main (string[] args) {
            var client = new PostmarkClient("<server token>");
            var message = new PostmarkMessage() {
                From = "<sender address>",
                To = "<recipient address>",
                Subject = "Hello from C#",
                TextBody = "Just a simple text body, nothing to see here. :-)"
            };
            //Start the task on a background thread.
            var pendingSend = Task.Run(() => client.SendMessageAsync (message));
            //Wait for the task to finish syncronously.
            pendingSend.Wait();
            // "CompletedSuccessfully" means that the task ran to completion without
            // generating an exception or being cancelled. Check the status of the
            // send from the api response.
            if (pendingSend.IsCompletedSuccessfully) {
                Console.WriteLine("Send completed, status is: {0}", pendingSend.Result.Status);
            }else{
                Console.WriteLine("Sending failed due to an exception or cancellation.");
            }
        }
    }
}

Web app example

async void SendMessage () { 

    try {
        var client = new PostmarkClient("<server token>");
        var message = new PostmarkMessage() {
            From = "<sender address>",
            To = "<recipient address>",
            Subject = "Hello from C#",
            TextBody = "Just a simple text body, nothing to see here. :-)"
        };
        var result = await client.SendMessageAsync(message);
        Console.WriteLine("Send completed, status is: {0}", result.Status);
    } catch (Exception ex) {
        Console.WriteLine("Sending failed due to reason: {0}", ex.Message);
    }
}

In addition to the examples above, Microsoft has a great article about these quirks, and some options for how to resolve them.

Last updated June 10th, 2020

Still need some help?

Our customer success team has your back!