I'm using a BluetoothClient on a background thread to poll for a BT client and connect once there. My thread's code looks something like this:
while (true)
{
try
{
using (var client = new BluetoothClient { InquiryLength = TimeSpan.FromSeconds(INQUIRY_MAX_DURATION)} )
{
var curAddr = ...;
var ep = new BluetoothEndPoint(curAddr, BluetoothService.SerialPort);
client.Connect(ep);
if (client.Connected)
{
using(var stream = client.GetStream())
{
try
{
//Do stuff on stream
}
catch(IOException) { }
}
}
}
}
catch (PlatformNotSupportedException)
{
Thread.Sleep(STACK_NOT_FOUND_RETRY_INTERVAL);
}
catch (SocketException ex)
{
Thread.Sleep(CONNECTION_FAILED_RETRY_INTERVAL);
}
}
This does connect and work correctly on the most computers, including the MS Surface with windows 8.1 Pro as long as it does not enter suspend. If I disable the surface and leave it alone for a while so it enters suspend, after turning on all Connect() attempts are throwing a SocketException saying the was invalid. It only recovers if I close and restart the app.
This condition does NOT happen if I set aircraft mode or pull the Bluetooth dongle on a PC, it seems to happen exclusively after the tablet's suspend. It seems not to matter whether the system has entered suspend in a connected or disconnected state.
What can I do to avoid this state or recover properly?
EDIT: API sniffing shows that an "WSAEINVAL" error is constantly thrown by the unmanaged WSAConnect function.
Building a 32feet.NET Version against .NET 4.0 instead of the older Framework Version provided by NuGet has solved the issue. Seems like something has been changed in .NET Sockets which has eliminated the issue.