Материал из .Net Framework эксперт
Multithreading in Windows Forms
using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
class Program : Form
{
private System.Windows.Forms.ProgressBar _ProgressBar;
[STAThread]
static void Main()
{
Application.Run(new Program());
}
public Program()
{
InitializeComponent();
ThreadStart threadStart = Increment;
threadStart.BeginInvoke(null, null);
}
void UpdateProgressBar()
{
if (_ProgressBar.InvokeRequired){
MethodInvoker updateProgressBar = UpdateProgressBar;
_ProgressBar.Invoke(updateProgressBar);
}else{
_ProgressBar.Increment(1);
}
}
private void Increment()
{
for (int i = 0; i < 100; i++)
{
UpdateProgressBar();
Thread.Sleep(100);
}
if (InvokeRequired)
{
Invoke(new MethodInvoker(Close));
}else{
Close();
}
}
private void InitializeComponent()
{
_ProgressBar = new ProgressBar();
SuspendLayout();
_ProgressBar.Location = new Point(13, 17);
_ProgressBar.Size = new Size(267, 19);
ClientSize = new Size(292, 53);
Controls.Add(this._ProgressBar);
Text = "Multithreading in Windows Forms";
ResumeLayout(false);
}
}
Mutex and UI
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
using System.Threading;
public class MutexForm : System.Windows.Forms.Form
{
private Mutex m = new Mutex( false, "WinMutex" );
private bool bHaveMutex = false;
public MutexForm()
{
Thread T = new Thread( new ThreadStart( ThreadProc ) );
T.Start( );
}
protected override void OnPaint( PaintEventArgs e ) {
if( this.bHaveMutex )
DrawCircle( System.Drawing.Color.Green );
else
DrawCircle( System.Drawing.Color.Red );
}
protected void DrawCircle( System.Drawing.Color color ) {
using(Brush b = new SolidBrush( color )){
using(Graphics g = this.CreateGraphics( )){
g.FillEllipse( b, 0, 0, this.ClientSize.Width, this.ClientSize.Height );
}}
}
protected void ThreadProc( ) {
while( true ) {
m.WaitOne( );
bHaveMutex = true;
Invalidate( );
Update( );
Thread.Sleep( 1000 );
m.ReleaseMutex( );
bHaveMutex = false;
Invalidate( );
Update( );
}
}
[STAThread]
static void Main()
{
Application.Run(new MutexForm());
}
}