Managed process and Windows API Mutex WaitForSingleObject always == WAIT_TIMEOUT

I have .NET Framework 2.0 Windows Forms Application, that uses unmanaged DLL. In this DLL I' have some areas, that is blocked with mutex. Mutex is created in unmanaged class constructor:

SndFails::SndFails(void)
{
...
      hFailaPieejasMutex = CreateMutex(NULL, FALSE, NULL);
...
}

Later processes acquires lock by invoking this function:

void SndFails::BlockFile()
{
...
       switch(WaitForSingleObject(hFailaPieejasMutex, FailaPieejasMutexMaxWaitLaiks))
      {
// ERROR_POINT
         case WAIT_TIMEOUT:
            return SetError(LoadLibString(IDS_NEVAR_SAGAIDIT_PROCESU, errs, errlen), ERRORNR_FAILA_PIEEJA_BLOKETA_CROSSTHREAD);

        case WAIT_OBJECT_0:
             return ERRORNR_NAV_KLUDA;

          case WAIT_ABANDONED:
             return ERRORNR_NAV_KLUDA;

          case WAIT_FAILED:
           FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), 0, errs, errlen, NULL);
           return SetError(errs, ERRORNR_FAILA_PIEEJA_BLOKETA_CROSSTHREAD);
      }

      return ERRORNR_NAV_KLUDA;
}

----
This method is called to unlock:

void SndFails::UnblockFile()
{
      ReleaseMutex(hFailaPieejasMutex);
}

----
All functions are working fine and locking/unlocking is also going well (3x paralel threads).
But ... here comes the trouble:
If I create new Managed thread like:
ThreadPool.QueueUserWorkItem(new WaitCallback(ReadFileBackground), g);
or:
th = new Thread(new ParameterizedThreadStart(ReadFileBackground);
th.Start(g);
or:
myBackgroundWorker.RunAsync(g);
---

In than in managed method I invoke unmanaged function that in turn calls SndFails::BlockFile():
// Managed C# method
private void ReadFileBackground(object x)
{
// Invoke Native function
   ReadImagebackgroundUnmanagedClass(ClassPtr);
// This call invokes native class method, that in turns calls BlockFile().
// In this case at unmanaged BlockFile place ERROR_POINT, I have correct Mutex Handle, but function WaitForSingleObject(...) always fails with WAIT_TIMEOUT.

// I've checked 10x times - the file is not actually blocked at access time. The handle value is the same for all the threads.
}

void SndFile::ReadImagebackgroundUnmanagedClass()
{
  // This call to BlockFile() always results in WAIT_TIMEOUT
   if(BlockFile() != ERRORNR_NAV_KLUDA)
     return;

... Do Usefull stuff
}

------------------
For me it looks like Managed thread has some sort of handle problems.
Any ideas?
LVL 3
uldisAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

pkadianCommented:
I am not very much sure , how did you have created the object of SndFails and passed it to ReadImagebackgroundUnmanagedClass.
However what I can see here is that Mutex is not getting signaled . Means in BlockFile , you need to make ReleaseMutex(hFailaPieejasMutex) call after whatever is the case you have executed.
It seems any one thread has started and worked however after that it has not signaled by BlockFile and other threads were just waiting and got time out.
WaitForSingleObject request the ownership , where as you need to release the ownership by ReleaseMutex so that other thread can own it.
It seems you class object is global in this case where as in other cases you might have called the
UnblockFile explicitly to get the mutex release.
0
pkadianCommented:
You may be missing UnBlockFile call in ReadImagebackgroundUnmanagedClass.
Please check.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
uldisAuthor Commented:
Class pointer is instantinated in managed class this:

// Pointer to class is returned.
[DllImport("SndManagerWin.dll")]
static extern IntPtr CreateSndRecorder();

Mutex is released and acquired correctly, because there are 2x unmanaged threads + primary managed one - and they work well with acquiring and releasing mutex.
Problem arises, if I create managed thread, and than call method that tries to acquire mutex.
0
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

uldisAuthor Commented:
pkadian: I checked that - there are just 4 places in the program, where BlockFile()/UnBlockFile() is called. And there is no return/throw between those calls. And I can easily BlockFile() from any of unmanaged threads at any time.
0
pkadianCommented:
Still i would request to check the calls of UnblockFile , if it is with sync with the number of time you have called BlockFile and make sure it is getting executed also.
0
uldisAuthor Commented:
Ok, I'll look at UnblockFile count.
0
pkadianCommented:
If that is the case , can you please try once to create the named Mutex , and try to get the handle in managed code and then use it in managed code as you are using.
0
uldisAuthor Commented:
Thanks - found one place where i checked:

if(BlockFile())
{
... Do The stuff
  UnblockFile();
}

--- But I should use:
if(BlockFile() == ERRORNR_NAV_KLUDA)
{
... Do The stuff
  UnblockFile();
}
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.