Question

why System.Threading.WaitHandle.WaitOne() hasn't overload for the timeout parameters as available in standard .NET implementation: http://msdn.microsoft.com/en-us/library/cc189907(v=vs.110).aspx

It's very useful in working threads when, during thread sleep, thread is requested to stop from Main UI thread.. Other ways to implement it?

Example:

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;
    }
}

Thanks Frank for your (1000th!!) reply.

So my custom implementation for WaitHandle.WaitOne(int Timeout) has been:

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();
}

Is this the right way for?

Thanks

Was it helpful?

Solution

This one hasn't been implemented yet. You may use semaphore.tryAcquire instead.

Background: Due to its design, dot42 supports the entire Android API (C# classes are proxies and generated from the android.jar). But is supports only part of the .NET API because the .NET classes are handcrafted on top of the Android/Java API.

Related question: Java Equivalent of .NET's ManualResetEvent and WaitHandle

UPDATE

We released the API under Apache License 2.0 so anyone may contribute now. I also logged an issue.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top