using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
delegate void SetTextDelegate(string text, TextBox tb);
public Form1()
{
InitializeComponent();
}
private void SetText(string text, TextBox tb)
{
if (tb.InvokeRequired)
{
this.Invoke(new SetTextDelegate(SetText),
new object[] { text, tb });
}
else
tb.Text = text;
}
private void PauseFiveSeconds(AutoResetEvent are)
{
// Simulate database work that takes 5 seconds
Thread.Sleep(5000);
are.Set();
}
private void PauseEightSeconds(AutoResetEvent are)
{
// Simulate database work that takes 8 seconds
Thread.Sleep(8000);
are.Set();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = "Working...";
textBox2.Text = "Working...";
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadOneProc));
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadTwoProc));
}
private void ThreadOneProc(Object stateInfo)
{
AutoResetEvent wh = new AutoResetEvent(false);
RegisteredWaitHandle handle = ThreadPool.RegisterWaitForSingleObject(
wh,
new WaitOrTimerCallback(ThreadOneTimedOut),
null,
6000,
true);
PauseFiveSeconds(wh);
handle.Unregister(wh);
}
private void ThreadTwoProc(Object stateInfo)
{
AutoResetEvent wh = new AutoResetEvent(false);
RegisteredWaitHandle handle = ThreadPool.RegisterWaitForSingleObject(
wh,
new WaitOrTimerCallback(ThreadTwoTimedOut),
null,
6000,
true);
PauseEightSeconds(wh);
handle.Unregister(wh);
}
private void ThreadOneTimedOut(Object state, bool timedOut)
{
SetTextDelegate st = new SetTextDelegate(SetText);
if (timedOut)
st("Timed Out", textBox1);
else
st("Completed", textBox1);
}
private void ThreadTwoTimedOut(Object state, bool timedOut)
{
SetTextDelegate st = new SetTextDelegate(SetText);
if (timedOut)
st("Timed Out", textBox2);
else
st("Completed", textBox2);
}
}
}
|