473,836 Members | 1,996 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Invoking a function from within a class...

I'm trying to have a class, which uses threads be able to raise events
to the form that created it. I've seen solutions around the net for
this, but I didn't really like their implementation. Most involve
passing the form into the class, or require a lot of coding. All I
really need to do is be able to have my thread call a function within
that class which runs on the same thread as the class. I've done this
from within forms, but can't figure out how to do it within a class
(see my comment below). How do I invoke the function from the thread
that the class is created on? I don't want the form to have to invoke
it. Any suggestions?

Public Class myClass

Dim myThread As Thread

Private client As Socket

Public Sub start()

myThread = New Thread(AddressO f threadFun)
myThread .Start()

End Sub

Private Sub threadFun()

raiseThisEvent( CLASS_EVENTS.ST ART)

End Sub

Delegate Sub thisEventDelega te(ByVal thisEvent As CLASS_EVENTS)

Public Sub raiseThisEvent( ByVal thisEvent As CLASS_EVENTS)

if thisEvent = CLASS_EVENTS.ST ART then
RaiseEvent onStart()
end if

End Sub

Public Sub raiseClassEvent (ByVal thisEvent As CLASS_EVENTS)

Dim passDelegate As New thisEventDelega te(AddressOf
raiseThisEvent)

' **** This is what I'd do if it were in a form, how do I do
the same within a class?? ****
Me.Invoke(passD elegate, thisEvent)
' ****

End Sub

end class
Jun 27 '08 #1
5 2646
On 2008-06-25, hu************* *****@yahoo.com <hu************ ******@yahoo.co mwrote:
I'm trying to have a class, which uses threads be able to raise events
to the form that created it. I've seen solutions around the net for
this, but I didn't really like their implementation. Most involve
passing the form into the class, or require a lot of coding. All I
really need to do is be able to have my thread call a function within
that class which runs on the same thread as the class. I've done this
from within forms, but can't figure out how to do it within a class
(see my comment below). How do I invoke the function from the thread
that the class is created on? I don't want the form to have to invoke
it. Any suggestions?

Public Class myClass

Dim myThread As Thread

Private client As Socket

Public Sub start()

myThread = New Thread(AddressO f threadFun)
myThread .Start()

End Sub

Private Sub threadFun()

raiseThisEvent( CLASS_EVENTS.ST ART)

End Sub

Delegate Sub thisEventDelega te(ByVal thisEvent As CLASS_EVENTS)

Public Sub raiseThisEvent( ByVal thisEvent As CLASS_EVENTS)

if thisEvent = CLASS_EVENTS.ST ART then
RaiseEvent onStart()
end if

End Sub

Public Sub raiseClassEvent (ByVal thisEvent As CLASS_EVENTS)

Dim passDelegate As New thisEventDelega te(AddressOf
raiseThisEvent)

' **** This is what I'd do if it were in a form, how do I do
the same within a class?? ****
Me.Invoke(passD elegate, thisEvent)
' ****

End Sub

end class
You, take the form as ISyncronizeInvo ke parameter to your constructor. And
then use invoke and begin invoke from that interface. It seems, you don't like
that solution, but it is really the simplest and most flexable. First, you
don't have to care if it's a form or a cookpot being passed, as long as it
implments ISyncronizeInvo ke - and second, you can allow nothhing to avoid
syncronization all together if you don't need it:

public class NeedsSync
privatte _syncObject As ISyncronizeInvo ke

public sub new()
' do stuff
_syncObject = nothing
end sub

public sub new(byval syncObject as ISyncronizeInvo ke)
me.new()
_syncObject = syncObject
end sub

' do a bunch of stuff

private sub InvokeADelegate (byval del as delegate, byval params() as
object)
if not _syncOjbect is nothing then
_syncOjbect.Inv oke (delegate, params)
else
raiseevent delegate, params
end if
end sub
end class

Anyway, that is a bunch of air code (and not completely syntactically correct)
- but I think it should give you an idea of what I'm saying.

--
Tom Shelton
Jun 27 '08 #2
On 2008-06-25, Tom Shelton <to*********@co mcastXXXXXXX.ne twrote:
On 2008-06-25, hu************* *****@yahoo.com <hu************ ******@yahoo.co mwrote:
>I'm trying to have a class, which uses threads be able to raise events
to the form that created it. I've seen solutions around the net for
this, but I didn't really like their implementation. Most involve
passing the form into the class, or require a lot of coding. All I
really need to do is be able to have my thread call a function within
that class which runs on the same thread as the class. I've done this
from within forms, but can't figure out how to do it within a class
(see my comment below). How do I invoke the function from the thread
that the class is created on? I don't want the form to have to invoke
it. Any suggestions?
<snip>

By the way, you can also check for InvokeRequired if you'd like :)

private sub InvokeADelegate (byval del as delegate, byval params() as object)
if not _syncOjbect is nothing andalso _syncObject.Inv okeRequired then
_syncOjbect.Inv oke (delegate, params)
else
raiseevent delegate, params
end if
end sub
--
Tom Shelton
Jun 27 '08 #3
Thanks, but I think I may be a bit unclear as to how to use this (I'm
new to .NET). In your code, what calls the InvokeADelegate function?
What is the delegate that gets passed in? Could you provide an
example of how this is called?

What happens if the syncObject doesn't implement the delegate
function? Using this, wouldn't the form need to implement every event
that the class raises?

Is there any simpler way to just get the class to call a function from
within a thread that can raise an event from the same thread as the
caller?

If the thread is just raising events that basically pass status
messages back to the form, does this really need to be thread safe?
What's the dangers that all of this is protecting me from?

I wonder if I should just have the thread set flags as to the state of
the object (i.e. connected, disconnected, err, ect) and have the main
form use a timer to just poll the object flag and update the UI when
the state changes?

Thanks for your help!!
On Jun 25, 8:56*pm, Tom Shelton <tom_shel...@co mcastXXXXXXX.ne t>
wrote:
On 2008-06-25, Tom Shelton <tom_shel...@co mcastXXXXXXX.ne twrote:
On 2008-06-25, hurricane_numbe r_...@yahoo.com <hurricane_numb er_...@yahoo.co mwrote:
I'm trying to have a class, which uses threads be able to raise events
to the form that created it. *I've seen solutions around the net for
this, but I didn't really like their implementation. *Most involve
passing the form into the class, or require a lot of coding. *All I
really need to do is be able to have my thread call a function within
that class which runs on the same thread as the class. *I've done this
from within forms, but can't figure out how to do it within a class
(see my comment below). How do I invoke the function from the thread
that the class is created on? I don't want the form to have to invoke
it. *Any suggestions?

<snip>

By the way, you can also check for InvokeRequired if you'd like :)

private sub InvokeADelegate (byval del as delegate, byval params() as object)
* * * * if not _syncOjbect is nothing andalso _syncObject.Inv okeRequired then
* * * * * * * * _syncOjbect.Inv oke (delegate, params)
* * * * else
* * * * * * * * raiseevent delegate, params
* * * * end if
end sub

--
Tom Shelton
Jun 27 '08 #4
On Jun 25, 7:50*pm, hurricane_numbe r_...@yahoo.com wrote:
Thanks, but I think I may be a bit unclear as to how to use this (I'm
new to .NET). *In your code, what calls the InvokeADelegate function?
What is the delegate that gets passed in? *Could you provide an
example of how this is called?

What happens if the syncObject doesn't implement the delegate
function? *Using this, wouldn't the form need to implement every event
that the class raises?

Is there any simpler way to just get the class to call a function from
within a thread that can raise an event from the same thread as the
caller?

If the thread is just raising events that basically pass status
messages back to the form, does this really need to be thread safe?
What's the dangers that all of this is protecting me from?

I wonder if I should just have the thread set flags as to the state of
the object (i.e. connected, disconnected, err, ect) and have the main
form use a timer to just poll the object flag and update the UI when
the state changes?

Thanks for your help!!

On Jun 25, 8:56*pm, Tom Shelton <tom_shel...@co mcastXXXXXXX.ne t>
wrote:
On 2008-06-25, Tom Shelton <tom_shel...@co mcastXXXXXXX.ne twrote:
On 2008-06-25, hurricane_numbe r_...@yahoo.com <hurricane_numb er_...@yahoo.co mwrote:
>I'm trying to have a class, which uses threads be able to raise events
>to the form that created it. *I've seen solutions around the net for
>this, but I didn't really like their implementation. *Most involve
>passing the form into the class, or require a lot of coding. *All I
>really need to do is be able to have my thread call a function within
>that class which runs on the same thread as the class. *I've done this
>from within forms, but can't figure out how to do it within a class
>(see my comment below). How do I invoke the function from the thread
>that the class is created on? I don't want the form to have to invoke
>it. *Any suggestions?
<snip>
By the way, you can also check for InvokeRequired if you'd like :)
private sub InvokeADelegate (byval del as delegate, byval params() as object)
* * * * if not _syncOjbect is nothing andalso _syncObject.Inv okeRequired then
* * * * * * * * _syncOjbect.Inv oke (delegate, params)
* * * * else
* * * * * * * * raiseevent delegate, params
* * * * end if
end sub
--
Tom Shelton- Hide quoted text -

- Show quoted text -
Ok... here is a complete working example. The form, is simply a form
with a ListBox on it named uxpOutput. It has it's IntegralHeight
property set to false and it is docked to fill the form:

Option Strict On
Option Explicit On
Option Infer Off
Public Class MainForm
Private _t As Worker
Private Sub MainForm_Load(B yVal sender As System.Object, ByVal e
As System.EventArg s) Handles MyBase.Load
_t = New Worker(Me)
AddHandler _t.Event1, AddressOf Event1
AddHandler _t.Event2, AddressOf Event2
AddHandler _t.event3, AddressOf Event3
_t.Start()
End Sub

Private Sub Event1(ByVal sender As Object, ByVal e As EventArgs)
uxpOutput.Items .Add("Event1 Called")
End Sub
Private Sub Event2(ByVal sender As Object, ByVal e As EventArgs)
uxpOutput.Items .Add("Event2 Called")
End Sub
Private Sub Event3(ByVal sender As Object, ByVal e As EventArgs)
uxpOutput.Items .Add("Event3 Called")
End Sub

Private Sub MainForm_FormCl osing(ByVal sender As System.Object,
ByVal e As System.Windows. Forms.FormClosi ngEventArgs) Handles
MyBase.FormClos ing
_t.Stop()
End Sub
End Class

Here is the Worker definition:

Option Strict On
Option Explicit On
Option Infer Off

Imports System
Imports System.Componen tModel
Imports System.Threadin g

Public Class Worker
Private _syncObject As ISynchronizeInv oke
Private _runner As Thread
Private _cancel As Boolean

Public Sub New(ByVal syncObject As ISynchronizeInv oke)
_syncObject = syncObject
End Sub

Public Event Event1 As EventHandler
Public Event Event2 As EventHandler
Public Event Event3 As EventHandler

Public Sub [Start]()
If Not _cancel Then
_runner = New Thread(AddressO f DoWork)
_runner.Start()
End If
End Sub

Public Sub [Stop]()
_cancel = True
_runner.Join()
End Sub

Private Sub DoWork()
Dim i As Integer
Dim r As New Random()

Do Until _cancel
i = r.Next(1, 31)
Select Case i
Case 1 To 10
RaiseAnEvent(Ev ent1Event, New Object() {Me, New
EventArgs()})
Case 11 To 20
RaiseAnEvent(Ev ent2Event, New Object() {Me, New
EventArgs()})
Case 21 To 30
RaiseAnEvent(Ev ent3Event, New Object() {Me, New
EventArgs()})
End Select
Thread.Sleep(10 00)
Loop
End Sub

Private Sub RaiseAnEvent(By Val d As [Delegate], ByVal args() As
Object)
If Not d Is Nothing Then
If _syncObject Is Nothing Or Not
_syncObject.Inv okeRequired Then
d.Method.Invoke (d.Target, args)
Else
_syncObject.Inv oke(d, args)
End If
End If
End Sub

End Class

Anyway, if you comment out the addhandler statements, you will see
that only the events you subscribe to are raised - and they are raised
on the right thread :)

HTH

--
Tom Shelton
Jun 27 '08 #5
Thanks for your help, I'll give that a shot.

On Jun 26, 1:45*am, Tom Shelton <tom_shel...@co mcast.netwrote:
On Jun 25, 7:50*pm, hurricane_numbe r_...@yahoo.com wrote:
Thanks, but I think I may be a bit unclear as to how to use this (I'm
new to .NET). *In your code, what calls the InvokeADelegate function?
What is the delegate that gets passed in? *Could you provide an
example of how this is called?
What happens if the syncObject doesn't implement the delegate
function? *Using this, wouldn't the form need to implement every event
that the class raises?
Is there any simpler way to just get the class to call a function from
within a thread that can raise an event from the same thread as the
caller?
If the thread is just raising events that basically pass status
messages back to the form, does this really need to be thread safe?
What's the dangers that all of this is protecting me from?
I wonder if I should just have the thread set flags as to the state of
the object (i.e. connected, disconnected, err, ect) and have the main
form use a timer to just poll the object flag and update the UI when
the state changes?
Thanks for your help!!
On Jun 25, 8:56*pm, Tom Shelton <tom_shel...@co mcastXXXXXXX.ne t>
wrote:
On 2008-06-25, Tom Shelton <tom_shel...@co mcastXXXXXXX.ne twrote:
On 2008-06-25, hurricane_numbe r_...@yahoo.com <hurricane_numb er_...@yahoo.co mwrote:
I'm trying to have a class, which uses threads be able to raise events
to the form that created it. *I've seen solutions around the netfor
this, but I didn't really like their implementation. *Most involve
passing the form into the class, or require a lot of coding. *All I
really need to do is be able to have my thread call a function within
that class which runs on the same thread as the class. *I've done this
from within forms, but can't figure out how to do it within a class
(see my comment below). How do I invoke the function from the thread
that the class is created on? I don't want the form to have to invoke
it. *Any suggestions?
<snip>
By the way, you can also check for InvokeRequired if you'd like :)
private sub InvokeADelegate (byval del as delegate, byval params() asobject)
* * * * if not _syncOjbect is nothing andalso _syncObject.Inv okeRequired then
* * * * * * * * _syncOjbect.Inv oke (delegate, params)
* * * * else
* * * * * * * * raiseevent delegate, params
* * * * end if
end sub
--
Tom Shelton- Hide quoted text -
- Show quoted text -

Ok... here is a complete working example. *The form, is simply a form
with a ListBox on it named uxpOutput. *It has it's IntegralHeight
property set to false and it is docked to fill the form:

Option Strict On
Option Explicit On
Option Infer Off

Public Class MainForm
* * Private _t As Worker
* * Private Sub MainForm_Load(B yVal sender As System.Object, ByVal e
As System.EventArg s) Handles MyBase.Load
* * * * _t = New Worker(Me)
* * * * AddHandler _t.Event1, AddressOf Event1
* * * * AddHandler _t.Event2, AddressOf Event2
* * * * AddHandler _t.event3, AddressOf Event3
* * * * _t.Start()
* * End Sub

* * Private Sub Event1(ByVal sender As Object, ByVal e As EventArgs)
* * * * uxpOutput.Items .Add("Event1 Called")
* * End Sub
* * Private Sub Event2(ByVal sender As Object, ByVal e As EventArgs)
* * * * uxpOutput.Items .Add("Event2 Called")
* * End Sub
* * Private Sub Event3(ByVal sender As Object, ByVal e As EventArgs)
* * * * uxpOutput.Items .Add("Event3 Called")
* * End Sub

* * Private Sub MainForm_FormCl osing(ByVal sender As System.Object,
ByVal e As System.Windows. Forms.FormClosi ngEventArgs) Handles
MyBase.FormClos ing
* * * * _t.Stop()
* * End Sub
End Class

Here is the Worker definition:

Option Strict On
Option Explicit On
Option Infer Off

Imports System
Imports System.Componen tModel
Imports System.Threadin g

Public Class Worker
* * Private _syncObject As ISynchronizeInv oke
* * Private _runner As Thread
* * Private _cancel As Boolean

* * Public Sub New(ByVal syncObject As ISynchronizeInv oke)
* * * * _syncObject = syncObject
* * End Sub

* * Public Event Event1 As EventHandler
* * Public Event Event2 As EventHandler
* * Public Event Event3 As EventHandler

* * Public Sub [Start]()
* * * * If Not _cancel Then
* * * * * * _runner = New Thread(AddressO f DoWork)
* * * * * * _runner.Start()
* * * * End If
* * End Sub

* * Public Sub [Stop]()
* * * * _cancel = True
* * * * _runner.Join()
* * End Sub

* * Private Sub DoWork()
* * * * Dim i As Integer
* * * * Dim r As New Random()

* * * * Do Until _cancel
* * * * * * i = r.Next(1, 31)
* * * * * * Select Case i
* * * * * * * * Case 1 To 10
* * * * * * * * * * RaiseAnEvent(Ev ent1Event, New Object() {Me, New
EventArgs()})
* * * * * * * * Case 11 To 20
* * * * * * * * * * RaiseAnEvent(Ev ent2Event, New Object() {Me, New
EventArgs()})
* * * * * * * * Case 21 To 30
* * * * * * * * * * RaiseAnEvent(Ev ent3Event, New Object() {Me, New
EventArgs()})
* * * * * * End Select
* * * * * * Thread.Sleep(10 00)
* * * * Loop
* * End Sub

* * Private Sub RaiseAnEvent(By Val d As [Delegate], ByVal args() As
Object)
* * * * If Not d Is Nothing Then
* * * * * * If _syncObject Is Nothing Or Not
_syncObject.Inv okeRequired Then
* * * * * * * * d.Method.Invoke (d.Target, args)
* * * * * * Else
* * * * * * * * _syncObject.Inv oke(d, args)
* * * * * * End If
* * * * End If
* * End Sub

End Class

Anyway, if you comment out the addhandler statements, you will see
that only the events you subscribe to are raised - and they are raised
on the right thread :)

HTH

--
Tom Shelton
Jun 27 '08 #6

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

Similar topics

0
2125
by: Prasad | last post by:
We are invoking a SQL DTS component (lets call it Comp1) built by us in another component (Comp2).Comp1 was built by creating the DTS package using the SQL DTS wizard and then saving it as a VB .bas file - this was converted to .NET class module. To this module we added some cutom transformation tasks. An additional info - we are invoking Comp1 in a loop inside Comp2. The transformation succesfully happens for a few files in the list...
6
4627
by: Manuel | last post by:
Can I invoke a function before main I could do it by invoking it in a Global object's constructor . Is there any other method other than this. Manuel
6
6184
by: Patrick | last post by:
Following earlier discussions about invoking a .NET class library via ..NET-COM Interop (using regasm /tlb) at http://groups.google.com/groups?hl=en&lr=&threadm=%23Van7eSrEHA.4004%40TK2MSFTNGP10.phx.gbl&rnum=1&prev=/groups%3Fhl%3Den%26lr%3D%26selm%3D%2523Van7eSrEHA.4004%2540TK2MSFTNGP10.phx.gbl I have concluded that my .NET class library (following the suggestions. namely setting the marshall type, etc.) , I can 1) Invoke public methods...
22
2787
by: ypjofficial | last post by:
Is there any possibility of invoking the member functions of a class without creating an object (or even a pointer to ) of that class. eg. #include <iostream.h> class test { public: void fun() {
0
2022
by: Haxan | last post by:
Hi, I have an unmanaged application that converts a function pointer to a delegate and then pass this as a parameter(delegate) to a managed function which then invokes it. Currently Im able to jump to this unmanaged function, but the values of the parameters inside this function Im seeing are not correct(they have some garbage values). //unmanaged class (C++ application)
1
3741
by: hal9000cr | last post by:
We are running into some problems with the execution of DB2 stored procedures when their isolation level is set to: set transaction isolation level READ UNCOMMITTED, READ WRITE; This is a web application running in JBoss 4.0.1 where a standard DataSource in JBoss is defined for connections against a DB2 database on an AS/400 (VRM = V5R2M0). The driver is established as: <driver-...
3
1728
by: Thijs | last post by:
Hello everybody, I´ve got a problem that´s slightly complicated (at least to me it seems) so I will try to state it as clearly as possible. At a certain point in time, I start a second thread that runs one of my functions. The function in this second raises events. As you might know, the eventhandler for this event is executed within this second thread and not within the first. It´s not possible to update properties of a user control...
6
1737
by: Fred | last post by:
Is it legal to invoke my destructor from within an instance function? For example, bool MyClass::someFunction() { SomeOtherClass:someFunction(this); // No other references to 'this' // after this point return true; }
2
5572
by: =?Utf-8?B?SmltIE93ZW4=?= | last post by:
Hi John, Hopefully this post will find its way back to you - or perhaps be answered by someone else. As I mentioned in my last post on the earlier portion of this thread, changing the serialization settings for the build handled the initial slows we encountered when invoking the web service. Since that time, we ported the original VB.net code over to C# - this was done to make it cleaner easier to include the project in the rest of...
0
9820
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9670
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10591
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9374
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7792
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5649
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4452
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4016
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3115
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.