Saturday, December 19, 2009

make your class provides asynchronous methods by very easy steps

You can provide an asynchronous API via your class in a few easy steps:
  • declare delegate with signature same as your method that you want to expose it as asynchronous.
  • declare private instance of the delegate.
  • wrap BeginInvoke and EndInvoke methods of the delegate.

1 public class TestClass

2 {

3 private delegate string sayHelloDelegate(string name);

4 sayHelloDelegate sayHello;

5

6 public string SayHello(string name)

7 {

8 return string.Format("Hello {0}", name);

9 }

10 public IAsyncResult BeginSayHello(string name, AsyncCallback callback, object @object)

11 {

12 sayHello = new sayHelloDelegate(SayHello);

13 return sayHello.BeginInvoke(name, callback, @object);

14 }

15 public string EndSayHello(IAsyncResult result)

16 {

17 return sayHello.EndInvoke(result);

18 }

19 }

Wednesday, July 15, 2009