title: Two questions about AsyncCallback and IAsyncResult pattern
body: <p>Two questions on the callback pattern with AsyncCallback and IAsyncResult.</p>
  
  <p>I changed the question with a code example:</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Text;
  
  namespace TestAsync
  {
      class Program
      {
          private static Wrapper test = new Wrapper();
  
          static void Main(string[] args)
          {
              test.BeginMethod("parameter 1", "parameter 2", Callback);
              Console.ReadKey();
          }
  
          private static void Callback(IAsyncResult ar)
          {
              string result = test.EndMethod(ar);
          }
      }
  
      public interface ITest
      {
          IAsyncResult BeginMethod(string s1, string s2, AsyncCallback cb, object state);
          string EndMethod(IAsyncResult result);
      }
  
      public class Wrapper
      {
          private ITest proxy = new Test();
  
          public void BeginMethod(string s1, string s2, AsyncCallback cb)
          {
              proxy.BeginMethod(s1, s2, cb, proxy);
          }
  
          public string EndMethod(IAsyncResult result)
          {
              return ((ITest)(result.AsyncState)).EndMethod(result);
          }
      }
  
      public class Test : ITest
      {
          private string WorkerFunction(string a, string b)
          {
              // "long running work"
              return a + "|" + b;
          }
  
          public IAsyncResult BeginMethod(string s1, string s2, AsyncCallback cb, object state)
          {
              Func&lt;string, string, string&gt; function = new Func&lt;string, string, string&gt;(WorkerFunction);
              IAsyncResult result = function.BeginInvoke(s1, s2, cb, state);
              return result;
          }
  
          public string EndMethod(IAsyncResult result)
          {
              return (string)(result.AsyncState);
          }
      }
  
      public delegate TResult Func&lt;T1, T2, TResult&gt;(T1 t1, T2 t2);
  }
  </code></pre>
  
  <p>BEGIN EDIT<br>
  I am beginning to see what is going on.
  I have mixed up a WCF async pattern and a normal async pattern.
  In WCF one uses a proxy and the Begin- and EndMethod must be passed the proxy and not the function delegate. In the WCF case the casting works, in the normal case not.
  WCF uses the [OperationContract(AsyncPattern = true)] attribute probably to enforce a somewhat different pattern.
  END EDIT   </p>
  
  <p>Why the error on the line <code>return (string)(result.AsyncState);</code> ?<br>
  Exactly the same pattern in production code is ok.</p>
  
  <p>Secondly, why can I not debug code in BeginMethod of class Test?<br>
  I can only break in WorkerFunction.</p>