该方法GetItemSearchResponse
将通过多个控制台应用程序调用。 但我想通过一个调用此方法之一。 所以我申请互斥。 因此,这种方法将被锁定其他线程。
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;
}
}
但我得到的日志并不能令人信服的代码的正确执行。
----
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.
它应该像一个线程获得锁,它应该由该线程首先那么锁应该被其他线程获得释放。
我打电话控制台应用这种方法如下:
using (var client = new AWSItemSearchClient())
{
response = client.GetItemSearchResponse(itemSearch);
}
再有,上述方法是通过3个控制台应用程序调用,但锁是由两个线程,1总是获取和9如何可以均等地分配锁?