|
using System;
using ThreadBound;
using System.Threading;
namespace FormsTest
{
/// <summary>
/// This is the Worker-Class. It is very lightweight because the whole threading
/// overhead is just a bunch of attributes.
/// Event the event does not need much special attention.
/// </summary>
[ThreadBound(ThreadBoundAttribute.ThreadBinding.PoolContext)]
class NumberWorker : ThreadBoundObject, IDisposable
{
//-- This is the cancel-flag. It must be declared volatile because it's
// used from an other thread.
private volatile bool CancelFlag=false;
//-- This is the NewNumber-event. It is called from the worker-thread as soon
// as a new number is available.
public delegate void NewNumberHandler(int number);
public event NewNumberHandler NewNumber;
//-- This is the worker method. It creates a new number from 0 to limit every second.
// Because this method is marked as AsyncThreaded and it will be executed in a background
// thread and the method call will return immediately.
[AsyncThreaded]
public void CreateNumbers(int limit, int delay)
{
CancelFlag = false;
for (int i = 0; i <= limit; i++)
{
Thread.Sleep(delay);
if (NewNumber!=null)
NewNumber(i);
if (CancelFlag)
break;
}
}
//-- The FreeThreaded-attribute of this method allows it to be called from any thread.
// It does not have to wait for the other methods to finish and can set the cancel-
// flag at any time.
[FreeThreaded]
public void Cancel()
{
CancelFlag = true;
}
public void Dispose()
{
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.