Semaphore causing deadlock on WPF

DoAsync, ConnectFtpAsync, ConnectDbAsync all works on Console project when the number of tasks exceeds the semaphore’s limit.
However ConnectFtpAsync and ConnectDbAsync except DoAsync cause WPF project to freeze when the number of tasks exceeds the semaphore’s limit.

ButtonPressedAsync() which is the outermost call doesn’t use the ConfigureAwait(false) and ConfigureAwait(false) used at inner call shouldn’t matter.

Removing the ConfigureAwait(false) from inner calls didn’t solve the problem.
Removing semaphore or not exceeding the limit of semaphore solved the problem.

FluentFTP and Oracle is used for the given code.
3 examples are tested separately.

  1. Why do ConnectFtpAsync and ConnectDbAsync freeze WPF project?
  2. Why DoAsync doesn’t freeze WPF project?
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>
protected override async Task ExecuteAsync(CancellationToken ct)
{
await ButtonPressedAsync();
}
private static async Task ButtonPressedAsync()
{
try
{
var connectionLimit = 4;
var smph = new Semaphore(connectionLimit, connectionLimit);
var tasks = new List<Task>();
for (var i = 0; i < connectionLimit + 1; ++i)
tasks.Add(DoAsync(smph));
//for (var i = 0; i < connectionLimit + 1; ++i)
// tasks.Add(ConnectFtpAsync(smph));
//for (var i = 0; i < connectionLimit + 1; ++i)
// tasks.Add(ConnectDbAsync(smph));
await Task.WhenAll(tasks).ConfigureAwait(false);
}
catch (Exception ex)
{
;
}
}
private static async Task DoAsync(Semaphore smph)
{
smph.WaitOne();
await Task.Delay(500).ConfigureAwait(false);
smph.Release();
}
private static async Task ConnectFtpAsync(Semaphore smph)
{
smph.WaitOne();
var ftpConnection = new AsyncFtpClient(
host: "ip",
port: 21,
user: "id",
pass: "pswd");
await ftpConnection.Connect().ConfigureAwait(false);
smph.Release();
}
private static async Task ConnectDbAsync(Semaphore smph)
{
smph.WaitOne();
var credential = "credential";
using var dbConnection = new OracleConnection(credential);
await dbConnection.OpenAsync().ConfigureAwait(false);
await dbConnection.CloseAsync().ConfigureAwait(false);
smph.Release();
}
</code>
<code> protected override async Task ExecuteAsync(CancellationToken ct) { await ButtonPressedAsync(); } private static async Task ButtonPressedAsync() { try { var connectionLimit = 4; var smph = new Semaphore(connectionLimit, connectionLimit); var tasks = new List<Task>(); for (var i = 0; i < connectionLimit + 1; ++i) tasks.Add(DoAsync(smph)); //for (var i = 0; i < connectionLimit + 1; ++i) // tasks.Add(ConnectFtpAsync(smph)); //for (var i = 0; i < connectionLimit + 1; ++i) // tasks.Add(ConnectDbAsync(smph)); await Task.WhenAll(tasks).ConfigureAwait(false); } catch (Exception ex) { ; } } private static async Task DoAsync(Semaphore smph) { smph.WaitOne(); await Task.Delay(500).ConfigureAwait(false); smph.Release(); } private static async Task ConnectFtpAsync(Semaphore smph) { smph.WaitOne(); var ftpConnection = new AsyncFtpClient( host: "ip", port: 21, user: "id", pass: "pswd"); await ftpConnection.Connect().ConfigureAwait(false); smph.Release(); } private static async Task ConnectDbAsync(Semaphore smph) { smph.WaitOne(); var credential = "credential"; using var dbConnection = new OracleConnection(credential); await dbConnection.OpenAsync().ConfigureAwait(false); await dbConnection.CloseAsync().ConfigureAwait(false); smph.Release(); } </code>

    protected override async Task ExecuteAsync(CancellationToken ct)
    {
        await ButtonPressedAsync();
    }
    
    private static async Task ButtonPressedAsync()
    {
        try
        {
            var connectionLimit = 4;
            var smph = new Semaphore(connectionLimit, connectionLimit);
            var tasks = new List<Task>();
    
            for (var i = 0; i < connectionLimit + 1; ++i)
                tasks.Add(DoAsync(smph));
    
            //for (var i = 0; i < connectionLimit + 1; ++i)
            //    tasks.Add(ConnectFtpAsync(smph));
    
            //for (var i = 0; i < connectionLimit + 1; ++i)
            //    tasks.Add(ConnectDbAsync(smph));
    
            await Task.WhenAll(tasks).ConfigureAwait(false);
        }
        catch (Exception ex)
        {
            ;
        }
    }
    
    private static async Task DoAsync(Semaphore smph)
    {
        smph.WaitOne();
    
        await Task.Delay(500).ConfigureAwait(false);
    
        smph.Release();
    }
    
    private static async Task ConnectFtpAsync(Semaphore smph)
    {
        smph.WaitOne();
    
        var ftpConnection = new AsyncFtpClient(
            host: "ip",
            port: 21,
            user: "id",
            pass: "pswd");
    
        await ftpConnection.Connect().ConfigureAwait(false);
    
        smph.Release();
    }
    
    private static async Task ConnectDbAsync(Semaphore smph)
    {
        smph.WaitOne();
    
        var credential = "credential";
        using var dbConnection = new OracleConnection(credential);
        await dbConnection.OpenAsync().ConfigureAwait(false);
        await dbConnection.CloseAsync().ConfigureAwait(false);
    
        smph.Release();
    }

Semaphore and other kernel events are not really compatible with async because they completely block execution.

So what you are getting is a classic Async Deadlock, because the code is being run on the UI thread and locking up waiting for the semaphore. This can be avoided using ConfigureAwait(false), but you need to ensure that that is used all the way down the stack, which in the case of external libraries is hard to ensure.

The real answer is to never block on async code. You need a wait event that can suspend execution via async, such as SempahoreSlim.

Note also that Release should be called in a finally to ensure it always gets called even in the event of an exception.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>private static async Task ButtonPressedAsync()
{
try
{
var connectionLimit = 4;
using var smph = new SemaphoreSlim(connectionLimit, connectionLimit);
var tasks = new List<Task>();
for (var i = 0; i < connectionLimit + 1; ++i)
tasks.Add(DoAsync(smph));
//for (var i = 0; i < connectionLimit + 1; ++i)
// tasks.Add(ConnectFtpAsync(smph));
//for (var i = 0; i < connectionLimit + 1; ++i)
// tasks.Add(ConnectDbAsync(smph));
await Task.WhenAll(tasks).ConfigureAwait(false);
}
catch (Exception ex)
{
;
}
}
private static async Task DoAsync(SemaphoreSlim smph)
{
await smph.WaitAsync();
try
{
await Task.Delay(500).ConfigureAwait(false);
// do other stuff
}
finally
{
smph.Release();
}
}
private static async Task ConnectFtpAsync(Semaphore smph)
{
await smph.WaitAsync();
try
{
// make sure to dispose your connection
using var ftpConnection = new AsyncFtpClient(
host: "ip",
port: 21,
user: "id",
pass: "pswd");
await ftpConnection.Connect().ConfigureAwait(false);
// do stuff with FTP connection
}
finally
{
smph.Release();
}
}
private static async Task ConnectDbAsync(Semaphore smph)
{
await smph.WaitAsync();
try
{
var credential = "credential";
await using var dbConnection = new OracleConnection(credential);
await dbConnection.OpenAsync().ConfigureAwait(false);
}
finally
{
smph.Release();
}
}
</code>
<code>private static async Task ButtonPressedAsync() { try { var connectionLimit = 4; using var smph = new SemaphoreSlim(connectionLimit, connectionLimit); var tasks = new List<Task>(); for (var i = 0; i < connectionLimit + 1; ++i) tasks.Add(DoAsync(smph)); //for (var i = 0; i < connectionLimit + 1; ++i) // tasks.Add(ConnectFtpAsync(smph)); //for (var i = 0; i < connectionLimit + 1; ++i) // tasks.Add(ConnectDbAsync(smph)); await Task.WhenAll(tasks).ConfigureAwait(false); } catch (Exception ex) { ; } } private static async Task DoAsync(SemaphoreSlim smph) { await smph.WaitAsync(); try { await Task.Delay(500).ConfigureAwait(false); // do other stuff } finally { smph.Release(); } } private static async Task ConnectFtpAsync(Semaphore smph) { await smph.WaitAsync(); try { // make sure to dispose your connection using var ftpConnection = new AsyncFtpClient( host: "ip", port: 21, user: "id", pass: "pswd"); await ftpConnection.Connect().ConfigureAwait(false); // do stuff with FTP connection } finally { smph.Release(); } } private static async Task ConnectDbAsync(Semaphore smph) { await smph.WaitAsync(); try { var credential = "credential"; await using var dbConnection = new OracleConnection(credential); await dbConnection.OpenAsync().ConfigureAwait(false); } finally { smph.Release(); } } </code>
private static async Task ButtonPressedAsync()
{
    try
    {
        var connectionLimit = 4;
        using var smph = new SemaphoreSlim(connectionLimit, connectionLimit);
        var tasks = new List<Task>();

        for (var i = 0; i < connectionLimit + 1; ++i)
            tasks.Add(DoAsync(smph));

        //for (var i = 0; i < connectionLimit + 1; ++i)
        //    tasks.Add(ConnectFtpAsync(smph));

        //for (var i = 0; i < connectionLimit + 1; ++i)
        //    tasks.Add(ConnectDbAsync(smph));

        await Task.WhenAll(tasks).ConfigureAwait(false);
    }
    catch (Exception ex)
    {
        ;
    }
}

private static async Task DoAsync(SemaphoreSlim smph)
{
    await smph.WaitAsync();
    try
    {
        await Task.Delay(500).ConfigureAwait(false);
        // do other stuff
    }
    finally
    {
        smph.Release();
    }
}

private static async Task ConnectFtpAsync(Semaphore smph)
{
    await smph.WaitAsync();
    try
    {
        // make sure to dispose your connection
        using var ftpConnection = new AsyncFtpClient(
            host: "ip",
            port: 21,
            user: "id",
            pass: "pswd");

        await ftpConnection.Connect().ConfigureAwait(false);
        // do stuff with FTP connection
    }
    finally
    {
        smph.Release();
    }
}

private static async Task ConnectDbAsync(Semaphore smph)
{
    await smph.WaitAsync();
    try
    {
        var credential = "credential";
        await using var dbConnection = new OracleConnection(credential);
        await dbConnection.OpenAsync().ConfigureAwait(false);
    }
    finally
    {
        smph.Release();
    }
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật