In My Sample UI, there are 3 buttons. Start button, pause, resume. The start button is async/await and will call a method:
private async void btnStart_Click()
{
await Task.Run(() => StartingMethod());
}
and we have a global ManualResetEvent
named _pauseEvent
.
and here is the structure of StartingMethod()
:
public void StartingMethod()
{
for (int i =0; i < 1000000; i++)
{
_pauseEvent.WaitOne();
// Do Something
}
}
and here is pause/resume buttons:
private async void btnPause_Click()
{
await Task.Run(() => _pauseEvent.Reset());
}
private async void btnResume_Click()
{
await Task.Run(() => _pauseEvent.Set());
}
but sometimes it will give The handle is invalid
for the ManualResetEvent
on pause/resume call. It seems it is a race condition problem. so I decided to create a global lock object.
Object _lockObject = new object();
and here is the new ones:
public void StartingMethod()
{
for (int i =0; i < 1000000; i++)
{
lock (_lockObject)
_pauseEvent.WaitOne();
// Do Something
}
}
private async void btnPause_Click()
{
await Task.Run(() => lock (_lockObject) _pauseEvent.Reset());
}
private async void btnResume_Click()
{
await Task.Run(() => lock (_lockObject) _pauseEvent.Set());
}
But it seems, here again, I will face a DeadLock problem with the lock object. How can I handle such a situation?