问题
The method GetItemSearchResponse
will be called by multiple console application. But I wanted to call this method one by one. So I applied mutex. So that this method will be locked for other threads.
public class AWSItemSearchClient : IDisposable
{
// the name of the global mutex;
private const string MutexName = "FAA9569-7DFE-4D6D-874D-19123FB16CBC-8739827-[SystemSpecicString]";
private Mutex _globalMutex;
private bool _owned = false;
//This method call should be synchronized
public ItemSearchResponse GetItemSearchResponse(ItemSearch itemSearch)
{
ItemSearchResponse response = null;
RequestAgain:
try
{
_globalMutex = new Mutex(true, MutexName, out _owned);
while (!_owned)
{
// did not get the mutex, wait for it.
_owned = _globalMutex.WaitOne(2000);
}
AWSECommerceServicePortTypeClient amazonClient = new AWSECommerceServicePortTypeClient();
response = amazonClient.ItemSearch(itemSearch);
Thread.Sleep(2000);
AppLogger.ExamineThreadAcquisitionLog("Lock acquired by Thread " + Process.GetCurrentProcess().Id + " Exe: " + AppDomain.CurrentDomain);
}
catch (Exception ex)
{
AppLogger.ExamineThreadAcquisitionLog("Error in Item Search request : " + ex.Message);
goto RequestAgain;
}
return response;
}
public void Dispose()
{
if (_owned)
{
_globalMutex.ReleaseMutex();
Thread.Sleep(1500);
AppLogger.ExamineThreadAcquisitionLog("Lock released by Thread " + Process.GetCurrentProcess().Id + " Exe: " + AppDomain.CurrentDomain);
}
_globalMutex = null;
}
}
But the log which I am getting is not convincing the proper execution of code.
----
Lock acquired by Thread 9916 Exe: Name:FB.ABC.vshost.exe
There are no context policies.
12/28/2016 5:27:06 PM
----
Lock Released by Thread 17396 Exe: Name:FB.XYZ.vshost.exe
There are no context policies.
12/28/2016 5:27:06 PM
----
Lock Released by Thread 9916 Exe: Name:FB.ABC.vshost.exe
There are no context policies.
12/28/2016 5:27:09 PM
----
Lock acquired by Thread 17396 Exe: Name:FB.XYZ.vshost.exe
There are no context policies.
12/28/2016 5:27:10 PM
----
Lock acquired by Thread 9916 Exe: Name:FB.ABC.vshost.exe
There are no context policies.
It should be like one thread got lock and it should be released by that thread first then the lock should be acquired by other thread.
I am calling this method in console apps as following :
using (var client = new AWSItemSearchClient())
{
response = client.GetItemSearchResponse(itemSearch);
}
Also the above method is called by 3 console apps but the lock is acquired always by two threads, 1 and 9. How can I distribute locks equally?
来源:https://stackoverflow.com/questions/41356577/issue-with-mutex-getting-lock-before-it-was-released-and-how-to-distribute-locks