Re: Smart Devices VB and C# Projects stopping the thread
gtamas
Hi,
a small example how to use the invoke. It is a part of a SignatureBox control
public class SignatureBox : PictureBox, IDisposable
{
private class DrawLineEventArgs : EventArgs
{
public readonly Pen Pen;
public readonly Point CurrentPoint;
public readonly Point NextPoint;
public DrawLineEventArgs( Pen oPen, Point oCurrentPoint, Point oNextPoint ) : base ()
{
this.Pen = oPen;
this.CurrentPoint = oCurrentPoint;
this.NextPoint = oNextPoint;
}
}
private delegate void DrawLineEvent( Object oSender, DrawLineEventArgs oEventArgs );
private delegate void OnUpdateEvent ();
...
// In this method will be the thread started
private void prepareWriting ()
{
if ( this.oWritingThread != null )
return;
this.OnDrawLine += new DrawLineEvent ( this.onDrawLineEventHandler );
this.OnUpdate += new OnUpdateEvent ( this.onUpdateEventHandler );
this.oWritingThread = new Thread ( new ThreadStart ( this.writeFromBuffer ) );
this.oWritingThread.Start ();
}
// This method runs in the thread
private void writeFromBuffer ()
{
while ( !this.bDisposed )
{
if ( this.qBuffer.Count == 0 )
Thread.Sleep ( this.iSleepPeriod );
// Hier will be the GUI updated
this.drawToGraphics ( );
}
this.bDisposed = false;
this.oWritingThread = null;
}
private void drawToGraphics ()
{
if ( this.qBuffer.Count == 0 )
return;
if ( this.oCurrentPoint == Point.Empty )
this.oCurrentPoint = ( Point ) this.qBuffer.Dequeue ();
Point oNextPoint;
int i = 0;
object[] aParams = new object[ 2 ];
aParams[ 0 ] = this;
while ( this.qBuffer.Count != 0 )
{
oNextPoint = ( Point ) this.qBuffer.Dequeue ();
// this.AdjusClipRectangle ( oNextPoint );
if ( oNextPoint == Point.Empty )
{
this.oCurrentPoint = oNextPoint;
break;
}
aParams[ 1 ] = new DrawLineEventArgs ( this.oPen, this.oCurrentPoint, oNextPoint );
// Here is an invoke with parameters
this.Invoke ( this.OnDrawLine, aParams );
this.oCurrentPoint = oNextPoint;
if ( i++ == this.iWaveSize )
break;
}
// Here is another without parameters
this.Invoke ( this.OnUpdate );
}
...
// *****************************
// Here comes the invoked methods
// Actually nothing special
private void onDrawLineEventHandler ( Object oSender, DrawLineEventArgs oEventArgs )
{
#region Drawing the line
this.oSignatureGraphics.DrawLine ( oEventArgs.Pen,
oEventArgs.CurrentPoint.X,
oEventArgs.CurrentPoint.Y,
oEventArgs.NextPoint.X,
oEventArgs.NextPoint.Y );
this.oSignatureGraphics.DrawLine ( oEventArgs.Pen,
oEventArgs.CurrentPoint.X + 1,
oEventArgs.CurrentPoint.Y,
oEventArgs.NextPoint.X + 1,
oEventArgs.NextPoint.Y );
this.oSignatureGraphics.DrawLine ( oEventArgs.Pen,
oEventArgs.CurrentPoint.X,
oEventArgs.CurrentPoint.Y + 1,
oEventArgs.NextPoint.X,
oEventArgs.NextPoint.Y + 1 );
#endregion
}
private void onUpdateEventHandler ()
{
base.Invalidate ();
base.Update ();
}
...
}
Have fun
Tamas