How to get the real-time network speed?

猫叔Vincent 16 Reputation points
2020-01-21T04:15:48.397+00:00

I used to get the data usage and divide the second ,but the result is always 0.

private async Task GetSpeed()  
        {  
            ConnectionProfile internetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();  
            var currentDate = DateTime.Now;  
            var startDate = DateTime.Now.AddSeconds(-2);  
  
            NetworkUsageStates NetworkUsageStates = new NetworkUsageStates();  
            NetworkUsageStates.Roaming = TriStates.No;  
            NetworkUsageStates.Shared = TriStates.No;  
  
            // dierctly using  NetworkUsageStates object without setting roaming and shared property will get null result.  
            //var networkUsage = await internetConnectionProfile.GetNetworkUsageAsync(utcTimeA, utcTimeB, DataUsageGranularity.Total, new NetworkUsageStates()) ;  
            var networkUsage = await internetConnectionProfile.GetNetworkUsageAsync(startDate, currentDate, DataUsageGranularity.Total, NetworkUsageStates);  
            foreach (var usage in networkUsage)  
            {  
                var received = usage.BytesReceived / 2 / 1000000;  
                var sent = usage.BytesSent / 2 / 1000000;  
                tb.Text = "Down:" + received + "Mb " + "Up: " + sent + "Mb";  
            }  
        }  

So how to get the real-time network speed?

Universal Windows Platform (UWP)
0 comments No comments
{count} vote

1 answer

Sort by: Most helpful
  1. Richard Zhang-MSFT 6,936 Reputation points
    2020-01-21T08:01:47.43+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    Did you use a network proxy such as a VPN when testing? In my test, normal traffic data cannot be obtained when the VPN is enabled.

    Maybe you can try another special method to connect with StreamSocket for downlink speed:

    public async Task GetNetworkSpeed()  
    {  
        double currentSpeed = 0;  
        var socket = new StreamSocket();  
        socket.Control.NoDelay = true;  
        socket.Control.QualityOfService = SocketQualityOfService.LowLatency;  
        socket.Control.KeepAlive = false;  
        using (socket)  
        {  
            await socket.ConnectAsync(new HostName("bing.com"), "80", SocketProtectionLevel.PlainSocket);  
            currentSpeed = socket.Information.RoundTripTimeStatistics.Min / 1000000.0;  
        }  
        return currentSpeed;  
    }  
    

    Thanks.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.