473,770 Members | 2,160 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Threading problem (incredibly straightforward mutex usage not working)

I've been having strange thread conflicts, and after moving the relevant
mutex higher and higher I've finally determined that the mutex doesn't
seem to be working at all.

Here is the relevant code:

private static Mutex previewMutex = new Mutex();

private static void preview (string source, string target)
{
try
{
previewMutex.Wa itOne();
if (previewerThrea d != null && previewerThread .IsAlive)
{
evl.WriteEntry( "WaitingForPrev iewerThread");
previewerThread .Join();
evl.WriteEntry( "FinishedWaitin g");
}
DocSearch.previ ewSource = source;
DocSearch.previ ewTarget = target;
previewerThread = new Thread (DocSearch.prev iewStarter);
previewerThread .Priority = ThreadPriority. Normal;
previewerThread .Name = "PreviewDownloa der";

previewerThread .Start();
previewMutex.Re leaseMutex();
}
catch(Exception err)
{
evl.WriteEntry( err.ToString()) ;
}
}
What's happening is the mutex is not blocking properly. I look in the
event log and see the WaitingForPrevi ewerThread message three times in a
row, with no messages at all in between. I've verified that log message
isn't anywhere else in the code and this is the only place previewMutex
is used. The really messed up thing is that this function is only
called from a GUI event handler (OnChange event for a ListView). From
my understanding from doing MFC and Win32 programming, the GUI should
only have one active thread by default anyway, meaning this shouldn't be
possible regardless of the mutex. The code works as expected if the
user slowly arrows through the listbox including all the expected event
log messages.

Here's what the thread does, if it matters:

public static void backgroundPrevi ew()
{
try
{
Common.GetFile( DocSearch.previ ewSource,DocSea rch.previewTarg et);

Common.SendMess age (Common.mainHwn d, Common.WM_PREVI EWREADY, 0, 0);
}
catch (Exception err)
{
evl.WriteEntry( err.ToString()) ;
}
}

GetFile calls a web service and downloads a file. SendMessage is the
win32 API.
The handler for WM_PREVIEW is in the same form class that activates the
thread, and it displays a picture in an activeX control.

Any help is greatly appreciated!

Tyler
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #1
11 3086
Tyler Sample <st**@qwest.net > wrote:
I've been having strange thread conflicts, and after moving the relevant
mutex higher and higher I've finally determined that the mutex doesn't
seem to be working at all.


Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #2
The Mutex.WaitOne will not block if no other thread has acquired the mutex. You don't show any other thread attempting to acquire the mutex. What behavior were you expecting from the Mutex?

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

I've been having strange thread conflicts, and after moving the relevant
mutex higher and higher I've finally determined that the mutex doesn't
seem to be working at all.

<snip>
Nov 16 '05 #3
Somehow preview() is being entered two to three times without exiting
before the Join() blocks and locks up the whole application.

I'll try to do a sample application that demonstrates the problem..
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #4
Okay, I was unable to reproduce the problem in a simple application (big
surprise, right?)

The test application did seem to confirm my suspicion that the normal
behavior of the application is one thread per GUI. Debugging the
problem application SEEMS to confirm this (can't figure out how to
programmaticall y determine a thread's unique ID, though, so I'm not
sure)

What I'm ending up with is TWO messages, back to back in the event log
saying:
WaitingForPrevi ewerThread
GUI

Can everyone plainly see how this shouldn't be possible? The code is
failing to execute the "FinishedWaitin g" log entry and is somehow
disappearing into thin air (apparently releasing the mutex on its way
out). There's only one line of code between those two log entries!
WriteEntry throws exceptions when it fails.

Is it possible a control I'm using is hosing the code stack?
I really can't even imagine where to begin solving this problem, and I
must.

The other possibility is that I somehow am ending up with two GUI
threads provided by the system for a very short period of time, but that
seems less likely than hosed memory.

//This is part of the handler for an OnChange event:
private static void preview (string source, string target)
{
try
{
previewMutex.Wa itOne();
if (previewerThrea d != null && previewerThread .IsAlive)
{

evl.WriteEntry( "WaitingForPrev iewerThread\r\n "+Thread.Curren tThread.Name
);
previewerThread .Join();
evl.WriteEntry( "FinishedWaitin g");
}
DocSearch.previ ewSource = source;
DocSearch.previ ewTarget = target;
previewerThread = new Thread (DocSearch.prev iewStarter);
previewerThread .Priority = ThreadPriority. Normal;
previewerThread .Name = "PreviewDownloa der";
previewerThread .Start();
previewMutex.Re leaseMutex();
}
catch(Exception err)
{
evl.WriteEntry( err.ToString()) ;
}

}

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #5
Two things:

You must not use GUI elements from any thread other than the one that created them. I'm not sure whether thats what you mean by "normal behavior being one thread per GUI".

You can get hold of the thread id using AppDomain.GetCu rrentThreadId() ;

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

Okay, I was unable to reproduce the problem in a simple application (big
surprise, right?)

The test application did seem to confirm my suspicion that the normal
behavior of the application is one thread per GUI. Debugging the
problem application SEEMS to confirm this (can't figure out how to
programmaticall y determine a thread's unique ID, though, so I'm not
sure)

What I'm ending up with is TWO messages, back to back in the event log
saying:
WaitingForPrevi ewerThread
GUI

Can everyone plainly see how this shouldn't be possible? The code is
failing to execute the "FinishedWaitin g" log entry and is somehow
disappearing into thin air (apparently releasing the mutex on its way
out). There's only one line of code between those two log entries!
WriteEntry throws exceptions when it fails.

Is it possible a control I'm using is hosing the code stack?
I really can't even imagine where to begin solving this problem, and I
must.

The other possibility is that I somehow am ending up with two GUI
threads provided by the system for a very short period of time, but that
seems less likely than hosed memory.
Nov 16 '05 #6
Well, I meant that unless I specifically do GUI stuff in one of my
threads, I have only one thread that should handle user messages
(events, mouse moves, etc..)

Thanks for the tip on the thread id. It is the same thread. It's the
same thread somehow never completing the function, so I guess this isn't
a threading problem.

Damn...Now I just have no idea where to even start. I guess I eliminate
the unsafe ActiveX controls one by one and see if that helps...

Uggh.

Well, thanks for the help!

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #7
Do you you DoEvents in your code? This can cause re-entrancy

Also, if you call an MTA based COM component from an STA thread you can get re-entrancy

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

Well, I meant that unless I specifically do GUI stuff in one of my
threads, I have only one thread that should handle user messages
(events, mouse moves, etc..)

Thanks for the tip on the thread id. It is the same thread. It's the
same thread somehow never completing the function, so I guess this isn't
a threading problem.

Damn...Now I just have no idea where to even start. I guess I eliminate
the unsafe ActiveX controls one by one and see if that helps...

Uggh.

Well, thanks for the help!
Nov 16 '05 #8
No DoEvents. Not really sure about the MTA com components. That's
pretty possible. Although they certainly aren't called between the two
logging functions (one of which isn't firing). Also, wouldn't the mutex
keep that kind of expected/normal re-entrancy from happening? Somehow
that mutex is getting released, or there is a bug in the mutex class
itself, which I find unlikely.

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #9
The mutex won't prevent this as its thread sensitive. As its the same thread re-entering it will just aquire a second lock on the mutex

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

No DoEvents. Not really sure about the MTA com components. That's
pretty possible. Although they certainly aren't called between the two
logging functions (one of which isn't firing). Also, wouldn't the mutex
keep that kind of expected/normal re-entrancy from happening? Somehow
that mutex is getting released, or there is a bug in the mutex class
itself, which I find unlikely.

Nov 16 '05 #10

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

Similar topics

0
1761
by: Alina | last post by:
Hello I'm working with a disconnected DataSet and I wish to make thread-safe the "add new rows" method. I try like this, but does not work: public class MyXmlDataDoc { ..... System.Threading.Mutex m = null;
3
2817
by: ron | last post by:
If I use the System.Threading.ThreadPool.QueueUserWorkItem to spawn a new threaded process, will this process be executed regardless of whether or not the current process ends prior to completion of the child thread? Or do I need to create a new thread object and join it to my current thread in order to guarantee execution of code in a child process? -Ron
5
1692
by: ste | last post by:
this code not work: it is no possible Exit from Monitor Why ? thank ste //////// using System; using System.Collections;
4
4094
by: Bardo | last post by:
Hi, I have a situation where I am capturing both a WMI event utilising the "ManagementEventWatcher" in the "System.Management" namespace, and a corresponding event ("EntryWritten") raised from the "EventLog" object in the "System.Diagnostics" namespace. When a certain event occurrs, both a WMI event is raised, and an event log entry is written. The problem I have is that I need to capture both events and somehow correlate which WMI...
16
351
by: One Handed Man \( OHM - Terry Burns \) | last post by:
Sorry if this gets duplicated, but I posted it and cant see it for a long time so repost. . . I have an application which is writing to a graphics object, the main UI thread and a worker thread are writing to the same object, whats the best way to manage this ? Thanks OHM --
17
1454
by: One Handed Man \( OHM - Terry Burns \) | last post by:
Assumes a Form with a Panel on it., Does the Mutex have to be within the address of a thread start address ? Cheers - OHM '----------- *************** ---------------- Private endProgram As Boolean = False Dim image1 As Image = Image.FromFile("..\Images\gun.bmp")
6
1320
by: MobileBoy36 | last post by:
Hi All, I want to make a LogFile class that is thread safe. I use a Mutex for it. But the behavior of the class is not that normal. In a c# guide I read you can achieve it by simply using Mutex.Waitone and Mutex.ReleaseMutex. Is that right? What 's wrong with my sub Writelog then? Best regards, Mobileboy
2
2060
by: Jeroen | last post by:
Hi all, I've been trying to get my head around threading. Here's an example from the book I'm reading: /***************************/ Mutex m = null; const string name = "xyz"; try
126
6748
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: http://www.cse.wustl.edu/~schmidt/ACE.html the same way that the STL (and subsequently BOOST) have been subsumed? Since it already runs on zillions of platforms, they have obviously worked most of the kinks out of the generalized threading and processes idea (along with many...
0
9618
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
10260
Oralloy
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...
0
10101
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 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...
1
10038
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
6712
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5354
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
4007
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
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2850
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.