A class in my app starts a new thread, and fires events from within that
thread.
The result, if nothing is done to prevent it, is that the events are
executed in the wrong thread in a form having a member of that class.
A user class doesn't have an Invoke method: how can I make the worker
thread invoke the events in the main UI thread that created the class?
The approach I originally built in does NOT work (I found this out only by
accident, because a Windows.Forms.T imer I started in one of the the event
handlers never generated any Tick events.)
I had added a dummy control to the class:
Private Shared m_ctl As New Control
and wrapped all events in functions:
Private Delegate Sub d_RaiseConnect( )
Private Sub RaiseConnect()
If m_ctl.InvokeReq uired Then
m_ctl.Invoke(Ne w d_RaiseConnect( AddressOf RaiseConnect))
Else
RaiseEvent OnConnect()
End If
End Sub
The events are _still_ being fired from the wrong thread: Me.InvokeRequir ed
is True in the event handler in the form containing the class.
Upon entry of RaiseConnect in the worker thread, m_ctl.InvokeReq uired is
False.
I started thinking later that this is probably correct, as the control
doesn't have a window, so there's no need to use Invoke to access it, but
when I make it a TextBox instead of just "Control", it *still* says
InvokeRequired = False.
Making it an instance member instead of shared, or instantiating it in the
class constructor instead of through "as new", makes no difference either. 5 1499
On Thu, 02 Sep 2004 10:57:08 +0200, Lucvdv <re**********@n ull.net> wrote: A class in my app starts a new thread, and fires events from within that thread.
The result, if nothing is done to prevent it, is that the events are executed in the wrong thread in a form having a member of that class.
I found a way out, but it has a side effect: the class can now only be used
as member of a form, and not in a console application for example.
If there is a better solution I'd still like to know about it, because the
class handles communication between applications: there's no real reason
why it should only be used from within a form (I actually _did_ have test
and maintenance programs that ran as a console app in a previous version
of the project).
My current solution is to pass a reference of the parent form to the
class's constructor. Instead of a dummy control, it's now using the passed
form to call Invoke on.
Declaration of the class in the containing form becomes something like
Private m_Class As New TestClass(Me)
And in the class you find:
Public Sub New(ByRef Parent As Form)
m_Parent = Parent
End Sub
Private Delegate Sub d_FireTest()
Private Sub FireTest()
If m_Parent.Invoke Required Then
m_Parent.Invoke (New d_FireTest(Addr essOf FireTest))
Else
RaiseEvent TestEvent()
End If
End Sub
Hi,
Yes, I can reproduce the problem with your code. That is because control's
handle is not created when you call the InvokeRequired due to the winform's
optimization. WinForms are not thread-safe and require all calls
manipulating a control to be made on the control's owning UI thread.
System.Windows. Forms.Control provides the Invoke and InvokeRequired methods
to marshal calls onto this thread, but they are only valid if the control's
native handle already exists. If the control doesn't exist, then
InvokeRequired will always return false, which can lead to creating the
native handle on the wrong thread, which can cause data corruption and a
hung process.
To make the property work more proper, always make sure to call
InvokeRequired and Invoke on a control whose handle already exists.
IsHandleCreated may not be valid when called across threads due to a race
condition since WinForms may destroy the handle on another thread before
you have used it. Since you can safely call InvokeRequired on any control
with a window handle created on the main UI thread, it is safest to call it
on a known good control rather than on the control which you want to
manipulate.
You can create a control which will always keep its window handle by
creating one specifically for this purpose and maintaining a HandleRef to
it for the life of your application.
You may try to make a test by changing your code as below.
Public Sub New()
Debug.WriteLine (Thread.Current Thread.Name)
m_Ctl = New Control
Dim hwnd As IntPtr = m_Ctl.Handle // force the control's handle
to be created.
End Sub
Best regards,
Peter Huang
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.
On Mon, 06 Sep 2004 00:48:46 GMT, v-******@online.m icrosoft.com ("Peter
Huang") wrote: To make the property work more proper, always make sure to call InvokeRequired and Invoke on a control whose handle already exists.
Thanks.
So it is what I thought at one moment, but scratched from the list - the
handle didn't exist yet. I thought it wouldn't exist until a child window
had been created for the control, that it would have to be added to a form
first (but: see below).
Dim hwnd As IntPtr = m_Ctl.Handle // force the control's handle to be created.
What you put in the comment must have bitten me: I checked the handle's
numeric value in the debugger once, and got a value that was neither zero
nor 0xffffffff.
Just examining it must have caused it to be created.
I probably didn't let the program continue to the end at that time, or I
should have seen the difference.
I just tried it: break the program on "m_Ctl = New Control", expand m_Ctl
in the Locals pane, and the error doesn't occur.
Break it, do *not* expand m_Ctl, and the error occurs.
Hi Lucvdv,
When you attempt to access to the handle, the control's handle will be
created whether or not it is accessed from debugger or the running code.
Anyway this is a test, I think an official approach is to to use a control
on the form whose handle has been created as my last post said.
Best regards,
Peter Huang
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.
"Peter Huang" wrote: Hi Lucvdv,
When you attempt to access to the handle, the control's handle will be created whether or not it is accessed from debugger or the running code. Anyway this is a test, I think an official approach is to to use a control on the form whose handle has been created as my last post said.
Of course, but it requires the class to know something about the form
it's going to be used in.
I solved it like I already said near the start of this thread: the New()
constructor of the class requires a form to be passed, and it calls
invoke on that form.
PS, Peter: are those "Did the response to your question in thread..."
mails auto-generated? I already considered the thread closed, my last
message was meant as a comment only ;) This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Anthony_Barker |
last post by:
I have been reading a book about the evolution of the Basic
programming language. The author states that Basic - particularly
Microsoft's version is full of compromises which crept in along the
language's 30+ year evolution.
What to you think python largest compromises are?
The three that come to my mind are significant whitespace, dynamic
typing, and that it is interpreted - not compiled. These three put
python under fire and cause...
|
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.
"somethread.interrupt()" will wake somethread up when it's in
sleeping/waiting state.
Is there any way of doing this with python's thread? I suppose thread
interrupt is a very primitive functionality for stopping a blocked
thread.
|
by: David Harrison |
last post by:
I am working on an application on Mac OS X that calls out
to python via PyImport_ImportModule(). I find that if
the imported module creates and starts a python thread,
the thread seems to be killed when the import of
the module is complete. Is this expected? Does
python have to be in control to allow threads to run?
Would it be better to arrange things such that the
file is processed using PyRun_SimpleFile?
David S. Harrison
|
by: Antal Rutz |
last post by:
Hi, All!
I'm new to threading. I have some design questions:
Task: I collect data and store them in an RDBMS (mysql or pgsql)
The question is how to do that with threading?
The data-collecting piece of the code runs in a thread.
1. Open the db, and each thread writes the result immediately.
(Sub-question: which is better: cursor object passed to the thread
|
by: CK |
last post by:
I have the following code in a windows service, when I start the windows
service process1 and process2 work fine , but final process (3) doesnt get
called. i stop and restart the windows service and the final process(3) gets
called. what am I doing wrong with the threading? by the way
Directory.GetFiles(IncomingXMLPath1).Length is some global outcome from
process 1.
Thanks
1)
| |
by: Anthony Nystrom |
last post by:
What is the correct way to stop a thread? abort? sleep? Will it start up
again... Just curious... If the thread is enabling a form, if the form is
disposed is the thread as well?
Thanks,
Anthony Nystrom
|
by: Bob |
last post by:
- For cleanup, is it sufficient to set a Thread to Nothing after it's done?
- It is OK to pass objects out of the thread? (dumb question maybe but I
want to be sure)
- What's the best way to process messages coming out of a thread? I want to
queue them up, but MessageQueue doesn't look like what I need. Should I just
make my own queue class? If so I'll have to worry about enumerator
synchronization... a pointer to a 'best practice'...
|
by: DBC User |
last post by:
I have a background process which reads a table to see if there are any
pending requests. If there are any, then it will start a worker thread
(only 10 allowed at a time) and executes a method. In this method, I
iniate a PROCESS and on completion, it reduces the available worker
thread and continue.
I have couple of questions;
1. Since I am launching multiple threads on a same method, do I have to
take care of locking so that each one...
|
by: Steven |
last post by:
I am taking an "advanced" VB.Net course via web at a state university
toward an information science degree. This is my second VB class and
I am kind of disappointed in it. This week we covered threading. The
instructor is of the opinion that threading is not very useful and
glossed over the subject. At least he admitted that he was glossing
it over. I've noticed that many of the postings on this board have to
do with threading and I...
|
by: frankiespark |
last post by:
Hello all,
I was perusing the internet for information on threading when I came
across this group. Since there seems to be a lot of good ideas and
useful info I thought I'd pose a question.
Threading is a new concept for me to implement. Here is my problem.
I have a system that receives xml files and records their file
locations in a database. I can potentially receive thousands,
|
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...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
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,...
|
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
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...
|
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...
| |
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...
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |