Async

From no name for this wiki
Revision as of 07:25, 16 October 2014 by Claude (talk | contribs) (Converting old style to new style)
Jump to: navigation, search

async und await

Task.Run()

using System;
using System.Threading;
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.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            Console.WriteLine("Button_Click: " + Thread.CurrentThread.GetHashCode());
            string p = await Task.Run(() => { return GetString(); });
            myLabel.Content = p;
        }

        static string GetString()
        {
            //GetString wird nicht im UI Thread ausgeführt.
            Console.WriteLine("GetStringStart: " + Thread.CurrentThread.GetHashCode());
            System.Threading.Thread.Sleep(10000);
            Console.WriteLine("GetStringEnd: " + Thread.CurrentThread.GetHashCode());
            return "Hello World asynchronous";
            
        }
        
    }
}

Converting old style to new style

internal static class Extension
{
        private static void TransferCompletion<T>(
            TaskCompletionSource<T> tcs, System.ComponentModel.AsyncCompletedEventArgs e, 
    Func<T> getResult)
        {
            if (e.Error != null)
            {
                tcs.TrySetException(e.Error);
            }
            else if (e.Cancelled)
            {
                tcs.TrySetCanceled();
            }
            else
            {
                tcs.TrySetResult(getResult());
            }
        }

        public static Task<loginCompletedEventArgs> LoginAsyncTask(this YChatWebService.WebServiceControllerPortTypeClient client, string userName, string password)
        {
            var tcs = new TaskCompletionSource<loginCompletedEventArgs>();
            client.loginCompleted += (s, e) => TransferCompletion(tcs, e, () => e);
            client.loginAsync(userName, password);
            return tcs.Task;
        }
 }