1

Ok so I am aware there are some similar questions such as:

Adding and Removing Anonymous Event Handler Unsubscribe anonymous method in C#

But I don't understand the concept of delegates.

I am starting to use the Plugin.BLE in a .Net Maui app.

The scanning operation is started from a button and then either times out (by use of a Timer) or is stopped by pressing the button again.

However in my button command (MVVM) I have the following snippet of code:

      ...
      adapter.DeviceDiscovered += (s, a) =>
      {
        if (a.Device.Name != null && a.Device.Name != String.Empty)
        {
          ...
        }
      };

      await adapter.StartScanningForDevicesAsync();
      ...

I note that each time I hit the button I get two more discovered items (I'm not sure why I'm getting 2 yet?) (This is from Pixel 5 emulator)

This makes some kind of sense as I am adding another event to the same adapter!

So I need to convert the anonymous function

 adapter.DeviceDiscovered += (s, a) =>
 {
 }

into a non anonymous function, so that I can add the handler and then remove it when the timer stops or I stop the function.

I have no idea how to go about this, especially in dealing with the s and the a.

I'd be grateful for any pointers, code.

Thanks, G.

Edit: link to Plguin.BLE https://github.com/xabre/xamarin-bluetooth-le

gfmoore
  • 976
  • 18
  • 31
  • In order to do this, we will need to know the data types of `s` and `a`. Can you share the definition of `DeviceDiscovered`? We can get them from there. – John Wu Jul 02 '22 at 18:47
  • Side note: VS has "introduce variable" refactoring exactly for people who are not able to split expressions into separate statements... It works like `x += a + b;` -> `var temp = a + b; x += temp;`... – Alexei Levenkov Jul 02 '22 at 18:50
  • I put a breakpoint in and hovered over the parameters: a was Plugins.BLE.Android.Adapter and s was Plugin.BLE.Abstractions.EventArgs.DeviceEventArgs. Looks reasonable? – gfmoore Jul 03 '22 at 08:01

1 Answers1

0

Well, I am truly astonished by Visual Studio.

After hacking away for a while trying to create functions and delegates I commented out the code and typed in

adapter.DeviceDiscovered +=

and visual studio created the rest of the code and the event handler for me.

So I have:

adapter.DeviceDiscovered += Adapter_DeviceDiscovered;

...

private void Adapter_DeviceDiscovered(object s, Plugin.BLE.Abstractions.EventArgs.DeviceEventArgs a)
{
  Debug.WriteLine("Got here");
}

I changed the original sender to s and the original e to a to match the code I was using.

Well so far it seems to work.

Now all I need to do is figure out why this is getting called twice! :sigh. :)

gfmoore
  • 976
  • 18
  • 31