473,486 Members | 2,353 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Threading Issue

I am building a class that has a function that I would like to run
asycronously. When the function is complete I would like to notify the
calling thread by raising an event or using a delegate. The handler for the
event (or the delegate callback) should run in the parent thread - not on
the asyncronous thread created while the function ran.

So, basically, I want my parent (form, class, control) to call my class
function - which spawns a thread and does some work. Once this work is done
I want to notify the parent and allow it to process the result in the parent
thread. Simple? Maybe. I can't make it happen.

I tried messing around with the AsyncCallback and IAsyncResult methods using
delegates. This is all fine and good, however the callback runs in the
spawned thread and not the parent thread.

I found some dirty hacks that referenced the parent form when the class is
instantiated and using the forms "BeginInvoke" method to perform the
operation. That would be good if I could count on my class always being
instantiated by a form - but this class could be called from another class
or even a user control. That rules out that avenue.

So, my question is this. What is the best way to achieve asyncronous
execution with the ability to notify the main thread when the operation is
complete? Further, this ability needs to be totally invisible to the client.
Am I missing something with using a Delegate function and the ".BeginInvoke"
and ".EndInvoke" methods that is keeping me from being notified on the main
thread?

Here is my code for the class:
visual basic code:
Imports System
Imports System.Runtime.Remoting.Messaging

Public Delegate Function QueryCallback() As Boolean

Public Class cQuery

Public Test As Integer

Public Function Query() As Boolean
Dim I As Integer
' just tie up this thread for a little while.
For I = 1 To 1000000
Test = I
Next
Query = True
End Function

Public Function BeginQuery(ByVal aCallBack As AsyncCallback, ByVal
AsyncState As Object) As IAsyncResult
Dim cbQuery = New QueryCallback(AddressOf Query)
BeginQuery = cbQuery.BeginInvoke(aCallBack, AsyncState)
End Function

Public Function EndQuery(ByVal iaResult As IAsyncResult) As Boolean
Dim cbQuery As QueryCallback
Dim result As AsyncResult
result = CType(iaResult, AsyncResult)
cbQuery = result.AsyncDelegate
EndQuery = cbQuery.EndInvoke(iaResult)
End Function
End Class

Here is the code for my Form (to test):
visual basic code:
' snip - basic form with a button
Private tc As New cQuery()

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim ac As New AsyncCallback(AddressOf MyCallback)
If Thread.CurrentThread.Name Is Nothing Then
Thread.CurrentThread.Name = "MAIN THREAD"
Dim Result As IAsyncResult = tc.BeginQuery(ac, tc)
MessageBox.Show("Current Thread Name = " &
Thread.CurrentThread.Name)
Console.WriteLine("LEAVING BUTTON1_CLICK HANDLER!")
End Sub

Private Sub MyCallback(ByVal result As IAsyncResult)
Console.WriteLine("ENTERING CALLBACK")
tc.EndQuery(result)
MessageBox.Show("Current Thread Name = " &
Thread.CurrentThread.Name)
End Sub
Nov 21 '05 #1
1 1348
I understand your problem. More generally, one might have multiple threads
and each thread might have multiple outputs. Raising an event on a
particular thread sounds like a nice idea, but I dont think it can be done.
My answer to this program organization issue is as follows:

1. A class that contains a Queue property.
2. Thread-safe Enqueue and Dequeue methods (worker threads enqueue, the
calling thread dequeues)
3. What gets enqueued and dequeued is always an array of objects (I
sacrifice strong typing for flexibility). In my game, the zero'th entry is
always a string that defines what follows. Enqueue has an arg like 'ByVal
ParamArray Data() As Object'.
Dequeue is a function returning Object().
4. The class also has Form and Timer properties. If set to other than
Nothing, whenever data is enqueued, the class does an Invoke to enable the
timer for an immediate tick, and this is how the worker thread dings the main
thread. If you prefer, your main thread could just poll the queue.
5. Not essential to the concept is the fact that I actually use three
queues, flash, normal, and idle. Worker threads can enqueue to any queue,
but dequeue always gives preference to flash over normal, and normal over
idle. It is a useful gimmick for my apps, but it is not essential.
6. Total size of the class is about 60 lines of VB, maybe 100 total with
comments and whitespace.

I know this sounds like overkill given your question, but my multi-thread
programs evolved in this direction, and I am content with it. To me it is
just a bit of threading infrastructure. I also don't claim it is the best
way - it is just my way.

Finally, be advised - if your main thread is a form thread, then the 'dirty
hack' of some variant of Invoke is absolutely necessary.

Nov 21 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1437
by: Zuel | last post by:
Sup everyone! I wrote this code for Tomcat appserver but I am told from an associate that it has threading issues. The basic idea is to store a read only data table for everyone to use. It...
19
6440
by: Jane Austine | last post by:
As far as I know python's threading module models after Java's. However, I can't find something equivalent to Java's interrupt and isInterrupted methods, along with InterruptedException....
0
1856
by: James R. Saker Jr. | last post by:
I've got a: "start server thread > Queue object, start server thread <> Queue object, start parsing client < Queue object" application that's got me puzzled. Probably an easy threads issue, but...
77
5207
by: Jon Skeet [C# MVP] | last post by:
Please excuse the cross-post - I'm pretty sure I've had interest in the article on all the groups this is posted to. I've finally managed to finish my article on multi-threading - at least for...
3
5558
by: ELO | last post by:
Hi all Every week, I need to get two files on a remote server. I have developped a C# Windows Service with two System.Threading.Timer to do this task For the first one, the delay (TimeSpan...
13
1783
by: John | last post by:
I've got some reasonably complex business logic in my C# code, in a class called by a ASP.NET page. This takes around 3-4 seconds to execute. It's not dependent on SQL calls or anything like that....
4
1981
by: JimD | last post by:
Is this safe? Any pitfalls? I have done threading in regular C# apps, but haven't had a needs to do threading in ASP.Net, until now. The issue I have ran into is this: Our corporate portal...
2
1517
by: WXS | last post by:
When I see things in .NET 2.0 like obsoletion of suspend/resume because of the public reason MS gives of they think people are using them inappropriately.. use mutex, monitor and other...
0
3487
by: R K | last post by:
I am delevoping a Scheduler module whose functionality is to load the Scheduled Item Details every day (For this I have created a System.Threading.TimerCallBack with Timespan 1 day) in a stack. Once...
126
6599
by: Dann Corbit | last post by:
Rather than create a new way of doing things: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2497.html why not just pick up ACE into the existing standard:...
0
7105
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
6967
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7180
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
7341
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5439
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
4870
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4564
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3076
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
266
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.