我的代码中有一个位置,我需要等待在传感器上识别任一手指,或者用户按下一个键以中止此操作并返回主菜单。
我尝试使用带有Event
的条件变量和锁定概念之类的东西但是当我尝试提醒主线程时,没有任何反应。
CODE:
Monitor
答案 0 :(得分:5)
当我尝试提醒主线程时,没有任何反应。
那是因为主线程正在监视器上等待此处创建的对象:
private static object _syncFinger = new object(); // used for syncing
但是每个线程都会替换该对象值,然后向监视器发出 new 对象的信号。主线程不知道新对象,因此当然告知监视器该新对象对主线程没有影响。
首先,每次创建对象以便与lock
一起使用时,请将其设为readonly
:
private static readonly object _syncFinger = new object(); // used for syncing
它总是正确的做法,这将阻止你在线程等待时改变被监视对象的错误。
接下来,创建一个单独的字段来保存WinBioIdentity
值,例如:
private static WinBioIdentity _syncIdentity;
并使用 将结果传回主线程:
private static bool AttemptIdentify()
{
// waiting for either the user cancels or a finger is inserted
lock (_syncFinger)
{
_syncIdentity = null;
Thread tEscape = new Thread(new ThreadStart(HandleIdentifyEscape));
Thread tIdentify = new Thread(new ThreadStart(HandleIdentify));
tEscape.IsBackground = false;
tIdentify.IsBackground = false;
tEscape.Start();
tIdentify.Start();
Monitor.Wait(_syncFinger); // -> Wait part
}
// Checking the change in the locked object
if (_syncIdentity != null) // checking for identity found
{
Console.WriteLine("Identity: {0}", ((FingerData)_syncIdentity).Guid.ToString());
return true;
}
return false; // returns with no error
}
private static void HandleIdentifyEscape()
{
do
{
Console.Write("Enter 'c' to cancel: ");
} while (Console.ReadKey().Key != ConsoleKey.C);
LockNotify((object)_syncFinger);
}
private static void HandleIdentify()
{
WinBioIdentity temp = null;
do
{
Console.WriteLine("Enter your finger.");
try // trying to indentify
{
temp = Fingerprint.Identify(); // returns FingerData type
}
catch (Exception ex)
{
Console.WriteLine("ERROR: " + ex.Message);
}
// if couldn't identify, temp would stay null
if(temp == null)
{
Console.Write("Invalid, ");
}
} while (temp == null);
__syncIdentity = temp;
LockNotify(_syncFinger);
}
所有这一切,你应该更喜欢使用现代async
/ await
成语:
private static bool AttemptIdentify()
{
Task<WinBioIdentity> fingerTask = Task.Run(HandleIdentify);
Task cancelTask = Task.Run(HandleIdentifyEscape);
if (Task.WaitAny(fingerTask, cancelTask) == 0)
{
Console.WriteLine("Identity: {0}", fingerTask.Result.Guid);
return true;
}
return false;
}
private static void HandleIdentifyEscape()
{
do
{
Console.Write("Enter 'c' to cancel: ");
} while (Console.ReadKey().Key != ConsoleKey.C);
}
private static WinBioIdentity HandleIdentify()
{
WinBioIdentity temp = null;
do
{
Console.WriteLine("Enter your finger.");
try // trying to indentify
{
temp = Fingerprint.Identify(); // returns FingerData type
}
catch (Exception ex)
{
Console.WriteLine("ERROR: " + ex.Message);
}
// if couldn't identify, temp would stay null
if(temp == null)
{
Console.Write("Invalid, ");
}
} while (temp == null);
return temp;
}
以上是一个极少数的例子。最好使用AttemptIdentify()
方法async
本身,然后使用await Task.WhenAny()
代替Task.WaitAny()
。包含一些中断任务的机制也会更好,即一旦完成任务,你应该想要打断另一个,这样就不会继续尝试它的工作。
但是这些问题并非async
/ await
版本所独有,也不需要解决以改进现有代码。