No ParameterizedThreadStart? No problem.

No ParameterizedThreadStart? No problem.

  • Comments 1
The .NET Compact Framework is a subset of the .NET Framework.  As such, there are features and functionality that exist in the .NET Framework that do not in the .NET Compact Framework.  One such feature is ParameterizedThreadStart.

If your ThreadStart delegate needs data provided by the caller you can create a wrapper object for the method.  To get the data to the delegate, you pass the it as arguments to your wrapper object's constructor.  The delegate then accesses the data as member variables when performing its work.

//---------------------------------------------------------------------
//THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
//KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//PARTICULAR PURPOSE.
//---------------------------------------------------------------------
/// <summary>
/// Wrapper object for worker ThreadStart delegate
/// </summary>
class ThreadStartDelegateWrapper
{
    /// <summary>
    /// Number of worker iterations
    /// </summary>
    private Int32 m_Iterations;

    /// <summary>
    /// Constructor
    /// </summary>
    /// <param name="iterations>
    /// Number of worker iterations
    /// </param>
    public ThreadStartDelegateWrapper(Int32 iterations)
    {
        this.m_Iterations = iterations;
    }

    /// <summary>
    /// Worker thread delegate
    /// </summary>
    public void Worker()
    {
        for(Int32 i = 0; i < this.m_Iterations; i++)
        {
            // do some work
        }
    }
} // end of ThreadStartDelegateWrapper class

By creating an instance of the above class, you can pass your desired iterations to the Worker method. 

// create the wrapper object, passing in the desired number of iterations
ThreadStartDelegateWrapper wrapper = new ThreadStartDelegateWrapper(15);

// create and start the thread
ThreadStart ts = new ThreadStart(wrapper.Worker);
Thread t = new Thread(ts);
t.Start();

For clarity, the above example was shown on multiple lines.  I have often written the above on a single line.

new Thread(new ThreadStart(new ThreadStartDelegateWrapper(15).Worker)).Start();

Enjoy!
-- DK

Disclaimer(s):
This posting is provided "AS IS" with no warranties, and confers no rights.
Page 1 of 1 (1 items)