Is there any way to call asynchronously WITHOUT using the thread pool ?

S

Sidanalism

I miss the old way when asynchronous calls are driven my window messages.

Yes a thread pool might greatly improve application performance but there
are time I don't want my event to be fire in a thread differ from the
calling thread. When a delegate is called in another thread it could be
frustrating for I have to consider thread occurrence issues in all the codes
it may invoke along my event chain. Sure the "Control.BeginInvoke()" could
be a work around but it is not always a good solution for I have to create
and initialize a Control object in my main thread and shared for all other
classes.

Is there any way my "OnReceive()" TCP message handler to be called
aschronously in my main thread by default ??

Thanks in advance!
 
C

Chris Dunaway

Sidanalism said:
Is there any way my "OnReceive()" TCP message handler to be called
aschronously in my main thread by default ??

You can call *any* method asynchronously using a delegate. I'm not
sure about an event handler however. I suppose inside the OnReceive
event handler, you can call another method asynchronously which does
the actual work:

VB.Net code:

'The sig for this delegate matches "SubThatDoesTheWork" below

Private Delegate Sub InvokerDelegate(...)

Private Sub OnReceive(...)
Dim Invoker As New InvokerDelegate(AddressOf SubThatDoesTheWork)

'This calls the sub asynchronously
Dim AsyncResult As IAsyncResult
AsyncResult = Invoker.BeginInvoke(Nothing, Nothing)

'Do other work here while the sub is being executed

'You should always call EndInvoke. This could be done elsewhere as
well
'If the sub is not finished, EndInvoke will wait until it is.
Invoker.EndInvoke(AsyncResult)
End Sub

Private Sub SubThatDoesTheWork(...)
'Actual work here
End Sub


Take care that "SubThatDoesTheWork" does not try to access the UI
improperly. I'm not sure if that would be a cross thread call, in
which case it would have to be marshalled correctly to the UI thread.

Hope this helps,

Chris
 
D

Dave Sexton

Hi Sidanalism,

In a .NET 2.0 Windows Forms app you can use this method:

System.Windows.Forms.WindowsFormsSynchronizationContext.Current.Post

to run code asynchronously on the UI thread without having to create a
Control.
 

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