Yesterday I started playing with Microsoft CTP async library and I came across awaitable pattern ... I followed some tutoral, but I have a newer version of ctp that tutorial was refering to so all info about that was useless. After looking over the internet how the new pattern looks like and what it needs ... dead end. I could not found anything that would fully describe what it needs and how to implement it, so I started doing this and that modification and in the end this is what it came out ... but I'am just sceptical that this is the proper implementation.

So can someone look over the code and tell me if this is right or wrong, what is wrong and how the proper implementation would look like ... thanks in advance :)

namespace CTP_Testing
{
    using System;
    using System.Linq;
    using System.Net;
    using System.Threading;
    using System.Threading.Tasks;

    public class CustomAsync
    {
        public static CustomAwaitable GetSiteHeadersAsync(string url)
        {
            return new CustomAwaitable(url);
        }
    }

    public class CustomAwaitable
    {
        private readonly Task<string> task;
        private readonly SynchronizationContext ctx;

        public CustomAwaitable(string url)
        {
            ctx = SynchronizationContext.Current;
            this.task = new Task<string>(
                () =>
                    {
                        var req = (HttpWebRequest)WebRequest.Create(url);
                        req.Method = "HEAD";
                        var resp = (HttpWebResponse)req.GetResponse();
                        return this.FormatHeaders(resp.Headers);
                    });
        }
        public CustomAwaitable GetAwaiter() { return this; }
        public bool IsCompleted { get { return task.IsCompleted; } }
        public void OnCompleted(Action continuation)
        {
            task.ContinueWith(_ => ctx.Post(delegate { continuation(); }, null));
            task.Start();
        }
        public string GetResult() { return task.Result; }

        private string FormatHeaders(WebHeaderCollection headers)
        {
            var headerString = headers.Keys.Cast<string>().Select(
                item => string.Format("{0}: {1}", item, headers[item]));

            return string.Join(Environment.NewLine, headerString.ToArray());
        }
    }
}

Please take a look at series of posts on CTP async by Jon Skeet.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.