[Last Call] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 237
  • Last Modified:

Background Thread Raising Event in Main Thread

I'd like to be able to start a background thread that can raise events on the main thread. I know it's possible to effectively do this by calling Invoke() (or BeginInvoke()) on a form/control from within the code running on the background thread. But can this be done without a control object handling the switch from background thead to UI thread? For example, what if I need this behavior in a console application.

I've also read that vb.net 2005 will support a BackgroundWorker class to simplify the interaction with a background thread, but my understanding is that this too will utilize a control object. I'm somewhat new to vb.net, so perhaps it's possible to add a control to a console application anyway?
1 Solution
Event is raised in the context of caller thread. Raising event means that event source calls directly event handler of the client. This happens in the same thread where event source (caller) runs.
Invoke or BeginInvoke allow to call functions of Windows forms in the thread where these forms are created. This is impossible in console application (unless it creates a window).
BackgroundWorker is component which simplifies writing of worker thread, but code produced by it doesn't contain any new features.
So, answer to your question is "No, it is impossible". Please describe your initial problem, maybe there is another solution for it.
Windows application or not, you can create a thread that can delegate an event. When the event is fired it will notify the calling program, in the case of a console application that might be pushing the limit a little.
zacbellAuthor Commented:
Sorry it took so long to reply. I have actually been trying different approaches with my code to either (a) achieve this desired behavior as stated, or (b) accept AlexFM's comment that it's impossible and rewrite my code to achieve the desired behavior using a different solution.

Basically, I was able to rewrite my code to achieve the desired functionality without using a background thread, and thus without worrying about the thread in which events are called, as suggested by AlexFM.

By the way, does anyone happen to know the easiest way to determine if a program was called from an interactive session, or was called non-interactively (i.e. was called from scheduler running on a server, and thus not within a user's session)?

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now