Esempio n. 1
0
        protected virtual void OnOnDiscovery(ServiceDiscoveryEventArgs e)
        {
            if (OnDiscovery != null)
            {
                var ls = OnDiscovery.GetInvocationList().Cast <EventHandler <ServiceDiscoveryEventArgs> >();//.Where(p => p.Invoke(this, e));

                foreach (var ev in ls)
                {
                    ev.Invoke(this, e);
                }
            }
        }
        /// <summary>
        /// Task to start network discovery. This task should be run indefinitely or for a certain timeframe.
        /// A cancellation token can be used to kill the background process.
        /// </summary>
        /// <param name="token">Cancellation token instance.</param>
        public async Task BackgroundQueueDiscovery(CancellationToken token)
        {
            SendDiscoveryMessage();

            UdpClient client = await CreateUdpClientAsync(token);

            // Run an infinite retry loop for discovery.
            while (true)
            {
                // With each try, check cancellation token and throw cancellation exception if cancelled.
                token.ThrowIfCancellationRequested();

                do
                {
                    try
                    {
                        UdpReceiveResult result = await client.ReceiveAsync();

                        string discoveredAddress = result.RemoteEndPoint.Address.ToString();

                        // Notify all subscribers that a new device has been found on the network.
                        if (!DiscoveredAddresses.Any(da => da.Equals(discoveredAddress)))
                        {
                            DiscoveredAddresses.Add(discoveredAddress);
                            OnDiscovery?.Invoke(discoveredAddress);
                        }
                    }
                    catch (Exception)
                    { }
                } while (client.Client != null);

                try
                {
                    client.Close();
                }
                catch (Exception)
                {
                }

                await CreateUdpClientAsync(token);
            }
        }
        protected virtual void OnOnDiscovery(ServiceDiscoveryEventArgs e)
        {
            //Task.Run(() => OnDiscovery?.Invoke(this, e));

            //OnDiscovery?.BeginInvoke(this, e, null, null);
            //OnDiscovery?.Invoke(this, e);

            if (OnDiscovery != null)
            {
                //var tasks = OnDiscovery.GetInvocationList().Cast<EventHandler<ServiceDiscoveryEventArgs>>().Select(s => s(this, e));

                var ls = OnDiscovery.GetInvocationList().Cast <EventHandler <ServiceDiscoveryEventArgs> >();//.Where(p => p.Invoke(this, e));

                foreach (var ev in ls)
                {
                    ev.Invoke(this, e);
                }


                //await Task.WhenAll(tasks);
            }
        }