Click here to Skip to main content
Licence CPOL
First Posted 5 Apr 2008
Views 10,065
Downloads 152
Bookmarked 16 times

WinForms lock detector

By | 5 Apr 2008 | Article
A nice and pretty simple C# class to detect if a GUI thread can not process window messages (and user actions).

lockdetector_bin

Introduction

If your application performs long operations sometimes and you do not want to spend time writing specialized code to show an indicator in every such place, then this class might help you.

Background

The idea is very simple. User actions such as keyboard and mouse events are just window messages. So, we can assume that your application is locked (processing a long operation) when your GUI thread (main thread, in most cases) can not process window messages.

The LockDetector class periodically calls BeginInvoke on some control from the target thread to send a window message. Then, if the delegate has not been called during a specified timeout interval, the OnLockDetected event is called in the detector thread and then can be processed in parallel with the thread being monitored.

Using the code

Check this very short example of how to use the class:

private LockDetector detector;
private void TestForm_Load(object sender, EventArgs e)
{
    detector = new LockDetector(this, 300); // detection timeout - 300ms
    detector.OnLockDetected += new 
      LockDetector.onLockDetectedDelegate(detector_OnLockDetected);
    detector.OnLockFinished += new 
      LockDetector.onLockFinishedDelegate(detector_OnLockFinished);
    detector.Start();
}

private void TestForm_FormClosing(object sender, FormClosingEventArgs e)
{
    detector.Dispose();
    detector = null;
}

void detector_OnLockFinished()
{
    MessageBox.Show("FINISHED");
}

void detector_OnLockDetected()
{
    MessageBox.Show("DETECTED");
}

private void button1_Click(object sender, EventArgs e)
{
    Thread.Sleep(5000);
}

The sources include a more advanced example.

History

  • 06 Apr 2008 - Initial release.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

diamond



Netherlands Netherlands

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120517.1 | Last Updated 6 Apr 2008
Article Copyright 2008 by diamond
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid