为什么System.Threading.WaitHandle.WaitOne()没有重载标准.NET实现中可用的超时参数:http://msdn.microsoft.com/en-us/library/cc189907(v=vs.110).aspx
在线程休眠期间,当请求线程停止主UI线程时,它在工作线程中非常有用。实现它的其他方法?
示例:
public void StartBatteryAnimation()
{
whStopThread = new ManualResetEvent(false);
batteryAnimationThread = new Thread(new ThreadStart(BatteryAnimation_Callback));
batteryAnimationThread.Start();
}
public void StopBatteryAnimation()
{
whStopThread.Set();
batteryAnimationThread.Join();
batteryAnimationThread = null;
whStopThread.Dispose();
whStopThread = null;
}
public void BatteryAnimation_Callback()
{
bool exitResult = false;
while (true)
{
// Do some stuff
exitResult = whStopThread.WaitOne(WAIT_INTERVALL);
if (exitResult) break;
}
}谢谢弗兰克给你的(第1000次!)回复。
因此,我为WaitHandle.WaitOne(int Timeout)定制的实现是:
private Thread batteryAnimationThread = null;
private Semaphore batteryAnimationSemaphore = null;
public void StartBatteryAnimation()
{
batteryAnimationSemaphore = new Semaphore(1);
batteryAnimationSemaphore.Acquire();
batteryAnimationThread = new Thread(new ThreadStart(BatteryAnimation_Callback));
batteryAnimationThread.Start();
}
public void StopBatteryAnimation()
{
batteryAnimationSemaphore.Release();
batteryAnimationThread.Join();
batteryAnimationThread = null;
batteryAnimationSemaphore = null;
}
public void BatteryAnimation_Callback()
{
bool stopThread = false;
try
{
while (true)
{
// Do some stuff..
stopThread = batteryAnimationSemaphore.TryAcquire(1, BATTERY_ANIMATION_INTERVALL, Java.Util.Concurrent.TimeUnit.MILLISECONDS);
if (stopThread) break;
}
catch (Exception ex)
{
}
batteryAnimationSemaphore.Release();
}这是正确的方式吗?
谢谢
发布于 2014-01-27 11:06:01
这一项还没有实施。您可以使用semaphore.tryAcquire代替。
背景:由于dot42的设计,它支持整个Android (C#类是代理,由android.jar生成)。但是is只支持.NET API的一部分,因为.NET类是在Android之上手工构建的。
相关问题:相当于.NET的ManualResetEvent和WaitHandle
更新
https://stackoverflow.com/questions/21378458
复制相似问题