|
using System;
using System.Threading;
using Amib.Threading;
namespace Examples
{
public class CallerState
{
private int _val = 0;
public int Value
{
get { return _val; }
}
protected void IncValue()
{
++_val;
}
}
public class NonDisposableCallerState : CallerState
{
public NonDisposableCallerState()
{
IncValue();
}
}
public class DisposableCallerState : CallerState, IDisposable
{
public DisposableCallerState()
{
IncValue();
}
#region IDisposable Members
public void Dispose()
{
IncValue();
}
#endregion
}
/// <summary>
/// Summary description for StateDisposeExample.
/// </summary>
public class StateDisposeExample
{
public StateDisposeExample()
{
}
/// <summary>
/// Example of non disposable caller state
/// </summary>
public bool TestDisposeCallerState()
{
STPStartInfo stpStartInfo = new STPStartInfo();
stpStartInfo.DisposeOfStateObjects = true;
SmartThreadPool smartThreadPool = new SmartThreadPool(stpStartInfo);
bool success = false;
CallerState nonDisposableCallerState = new NonDisposableCallerState();
CallerState disposableCallerState = new DisposableCallerState();
IWorkItemResult wir1 =
smartThreadPool.QueueWorkItem(
new WorkItemCallback(this.DoSomeWork),
nonDisposableCallerState);
IWorkItemResult wir2 =
smartThreadPool.QueueWorkItem(
new WorkItemCallback(this.DoSomeWork),
disposableCallerState);
wir1.GetResult();
success = (1 == nonDisposableCallerState.Value);
wir2.GetResult();
// Wait a little bit for the working thread to call dispose on the
// work item's state.
smartThreadPool.WaitForIdle();
success = success && (2 == disposableCallerState.Value);
smartThreadPool.Shutdown();
return success;
}
/// <summary>
/// Example of non disposable caller state
/// </summary>
public bool TestDontDisposeCallerState()
{
STPStartInfo stpStartInfo = new STPStartInfo();
stpStartInfo.DisposeOfStateObjects = false;
SmartThreadPool smartThreadPool = new SmartThreadPool(stpStartInfo);
bool success = false;
CallerState nonDisposableCallerState = new NonDisposableCallerState();
CallerState disposableCallerState = new DisposableCallerState();
IWorkItemResult wir1 =
smartThreadPool.QueueWorkItem(
new WorkItemCallback(this.DoSomeWork),
nonDisposableCallerState);
IWorkItemResult wir2 =
smartThreadPool.QueueWorkItem(
new WorkItemCallback(this.DoSomeWork),
disposableCallerState);
wir1.GetResult();
success = (1 == nonDisposableCallerState.Value);
wir2.GetResult();
success = success && (1 == disposableCallerState.Value);
smartThreadPool.Shutdown();
return success;
}
private object DoSomeWork(object state)
{
Thread.Sleep(1000);
return 1;
}
}
}
|
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.
B.Sc. in Computer Science.
Works as Software Developer.