Operation is not valid due to the current state of the object.

Jassim Al Rahma 1,526 Reputation points
2022-04-09T16:15:45.76+00:00

Hi,

Why i am getting this error:

Operation is not valid due to the current state of the object.

Here is my code:

public async void PingAsync()
{
    LabelRoundTrip.Text = "Pinging…";

    Ping ping = new Ping();
    PingReply pingReply = await ping.SendPingAsync("yahoo.com");

    LabelRoundTrip.Text = pingReply.Status.ToString();
}

Thanks,
Jassim

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,301 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,375 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,201 Reputation points
    2022-04-09T19:42:01.097+00:00

    Firs thing wrong, public async void PingAsync() is using void see my code.

    This works for me, give it a try.

    using System.Net.NetworkInformation;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace Standard1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                LabelRoundTrip.Text = @"Pinging…";
            }
    
            private async Task<string> PingTask()
            {
    
                var ping = new Ping();
                PingReply pingReply = await ping.SendPingAsync("yahoo.com");
    
                return  pingReply.Status.ToString();
    
            }
    
            private async void button1_Click(object sender, System.EventArgs e)
            {
                LabelRoundTrip.Text = @"Pinging…";
                var results = await PingTask();
                LabelRoundTrip.Text = results;
            }
        }
    }
    
    1 person found this answer helpful.