Click here to Skip to main content
15,894,646 members
Articles / Programming Languages / C#

Continuous asynchronous Ping using TAP and IProgress in C#5

Rate me:
Please Sign up or sign in to vote.
4.95/5 (23 votes)
15 Jan 2014CPOL4 min read 52.1K   3.2K   39  
This article shows how to use C# 5 async functions to create a continuous asynchronous ping and report progress to the UI.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;


/// From Mark Heath's blog Sound Code:
/// http://mark-dot-net.blogspot.de/2010/11/how-to-invoke-command-on-viewmodel-by.html
/// 
namespace PingWpf.ViewModels
{
    public static class EnterKeyHelpers
    {
        public static ICommand GetEnterKeyCommand(DependencyObject target)
        {
            return (ICommand)target.GetValue(EnterKeyCommandProperty);
        }

        public static void SetEnterKeyCommand(DependencyObject target, ICommand value)
        {
            target.SetValue(EnterKeyCommandProperty, value);
        }

        public static readonly DependencyProperty EnterKeyCommandProperty =
            DependencyProperty.RegisterAttached(
                "EnterKeyCommand",
                typeof(ICommand),
                typeof(EnterKeyHelpers),
                new PropertyMetadata(null, OnEnterKeyCommandChanged));

        static void OnEnterKeyCommandChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
        {
            ICommand command = (ICommand)e.NewValue;
            FrameworkElement fe = (FrameworkElement)target;
            Control control = (Control)target;
            control.KeyDown += (s, args) =>
                {
                    if (args.Key == Key.Enter)
                    {
                        // make sure the textbox binding updates its source first   
                        BindingExpression b = control.GetBindingExpression(TextBox.TextProperty);
                        if (b != null)
                        {
                            b.UpdateSource();
                        }
                        command.Execute(null);
                    }
                };
        }
    }


}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer evopro systems engineering AG
Germany Germany
Peter Butzhammer studied physics but decided to work as a software developer 10 years ago. He has a strong interest in statistics, simulation and functional programming.

Comments and Discussions