Quantcast
Channel: Recent Threads — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 204402

How to implement a timeout when using Bluetooth socket.ConnectAsyc()?

$
0
0

I am using the following method to implement a timeout on a Bluetooth socket.ConnectAsync() call in my xamarin.forms (shared) project:

private async Task<bool> Connect()
{
    int attempts = 3;
    bool success = false;

    for (int i = 0; i < attempts; i++)
    {
        await _socket.ConnectAsync();
        IAsyncResult result = _socket.ConnectAsync();
        success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), true);

        if (!success)
        {
            await Task.Delay(TimeSpan.FromSeconds(1));
        }
        else
        {
            break;
        }
    }

This works. However, each time a connection attempt is made, the UI thread is being blocked. The following lines block the UI thread because they do not support await:

IAsyncResult result = _socket.ConnectAsync();
success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), true);

To get this to run async, the IAsyncResult design pattern (Event-based Asynchronous Pattern) needs to be implemented, which I do not want to do. Is there some other way, using await, that I can apply a timeout to the _socket.ConnectAsync() call? Note that IAsyncResult can NOT be assigned using an await.


Viewing all articles
Browse latest Browse all 204402

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>