I have a class for doing Bluetooth communications, for the sake of argument let's say it looks something like this:
class Bluetooth
{
public delegate void ByteFunc (byte[] packet);
public event ByteFunc OnPacketSending;
public event ByteFunc OnPacketReceived;
public void SendPackets(List<byte[]> packets)
{
foreach (byte[] packet in packets)
{
OnPacketSending?.Invoke(packet);
Bluetooth_Send(packet); // Pseudo-code, takes a few more calls than this
}
}
}
The problem is that events are normally synchronous (right?) so if I add an event handler like this:
Bluetooth.OnPacketSending += (packet) => RedrawTheEntireScreenAndAllKindsOfStuff(packet);
And now I call SendPackets() in the UI thread, my Bluetooth communication is slowed way down because all that UI stuff is happening instead of the Bluetooth.
The compiler won't let me say
public async event ByteFunc OnPacketSending
or
await OnPacketSending?.Invoke(packet)
and I can't use Control.BeginInvoke() because I don't know if the event handler is in a control.
and most of the examples I've seen online put the responsibility on the event handler to do things asynchronously, and I'd rather be able to enforce it.
Is it sufficient/recommended to do something simple like:
Task.Factory.StartNew (() => OnPacketSending?.Invoke (packet));
Does this use a thread pool or similar to avoid swamping the poor mobile device?