I need help with asynchronous calls in C#

I

intrader

What I have is a class A with a method Foo. I would like to create a
thread that instances A and then calls Foo asynchronously while
performing other duties.

I think that the solution is to write an asynchronous version of Foo so
that the caller can pass a callback as in the signature:

public static IAsyncResult Foo(
FooParams fooParams,
AsyncCallback requestCallback,
object StateObject
);

Is this possible?

Thanks
 
N

Nicholas Paldino [.NET/C# MVP]

Well, the easiest way to do this is to create a delegate with the same
signature as foo, like so:

private delegate void AsyncFoo(FooParams fooParams);

Then implement your BeginFoo like so:

private static AsyncFoo asyncFoo;

public static IAsyncResult BeginFoo(FooParams fooParams, AsyncCallback
callback, object state)
{
// Store asyncFoo.
asyncFoo = new AsyncFoo(Foo);

// Make the call.
return asyncFoo.BeginInvoke(fooParams, callback, state);
}

public static void EndFoo(IAsyncResult result)
{
// Finish the call.
asyncFoo.EndInvoke(result);
}

If you are going to have multiple calls to BeginFoo, then you are going
to have to manage the asyncFoo field so that you don't have mismatched
begin/end calls.

Hope this helps.
 
P

Peter Duniho

[...]
I think that the solution is to write an asynchronous version of Foo so
that the caller can pass a callback as in the signature:

public static IAsyncResult Foo(FooParams fooParams,
AsyncCallback requestCallback, object StateObject);

Is this possible?

Yes, though unless you use Invoke or BeginInvoke to run the callback
delegate, it won't be run on the instantiating thread. One common way to
do what you want is to use a BackgroundWorker which provides a built-in
mechanism to run a callback when the thread has finished. You can, of
course, implement the whole thing yourself and it wouldn't even be that
hard, but it probably makes sense to just take advantage of the existing
class.

Pete
 
P

Peter Duniho

Yes, though unless you use Invoke or BeginInvoke to run the callback
delegate, it won't be run on the instantiating thread.

And I should clarify this:

Even if you *do* use Invoke or BeginInvoke, it won't run on the
instantiating thread unless you are using the Invoke/BeginInvoke method on
a form and the instantiating thread was that form's thread.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top