invoking on the console thread?

frumbert

New member
Joined
Jan 7, 2006
Messages
3
Programming Experience
3-5
In a windows forms app, It is my understanding that I can easily invoke on the forms underlying thread like this:

VB.NET:
Private Delegate Sub DelegateHandlerName(ByVal foo As Object)

Sub Main()
  Dim T As New Thread(AddressOf InvokeDelegate)
  T.IsBackground = True
  T.Start()
End Sub

Sub InvokeDelegate
  Dim dlg As New DelegateHandler(AddressOf DelegateHandlerName)
  Dim args() As Object = {my_object}
  Me.Invoke(dlg, args)
End Sub

Private Sub HandlerName(ByVal foo as Object)
  ' Do something on the main thread (not the T thread)
End Sub
How do I do the same thing on a console app, so that I invoke on the console app's main thread?
 
The usual reason to invoke a method via a delegate is to access a member of a control, which must be done on the UI thread. Given that there are no controls in Console apps, do you mind if I ask why exactly you want to do this?
 
I'm used to windows forms handling and haven't done much console work before, so i'm not sure what the right way of doing this is. I'm also not thread-savvy beyond what I listed above (I know it works and I know what it does, so I use it).

I have a socket listening on a background thread (so its buffering and so on don't interfere with the foreground thread execution - which it does if its all in the same thread). I want to pass the results (a object containing the socket itself) from the background thread to a handler in the foreground thread for queueing.
 
Like I said, the usual reason to use delegates to make cross-thread calls is the fact that accessing a member of a control across thread boundaries is not thread safe. If you aren't using controls then you don't have that issue. There's nothing to stop you accessing objects across thread boundaries in general. You should just make sure you synchronise that access properly so you don't have two threads interfering with one another. You should be using SyncLock blocks or Monitors to implement this, and also note the SyncRoot property and Synchronised method of most collection classes to make collection access thread safe.
 
ok thanks - i think. I actually didn't understand too much of that but at least you've given me enough places to start reading.
 
Back
Top