Threading 2!

M

Mike P

I am using the following code, what I need to know is, what do I do if I
want to pass parameters to DoSomeWork? I don't understand how the
callback variable is passed to DoSomeWork.

private void SpawnSomeWork()
{
IProgressCallback callback; // = ???
System.Threading.ThreadPool.QueueUserWorkItem(
new System.Threading.WaitCallback(
DoSomeWork ),
callback );
}

private void DoSomeWork( object status )
{
IProgressCallback callback = status as IProgressCallback;

try
{
callback.Begin( 0, 100 );
for( int i = 0 ; i < 100 ; ++i )
{
callback.SetText( String.Format( "Performing op: {0}", i )
);
callback.StepTo( i );
if( callback.IsAborting )
{
return;
}
// Do a block of work
if( callback.IsAborting )
{
return;
}
}
}
catch( System.Threading.ThreadAbortException )
{
// We want to exit gracefully here (if we're lucky)
}
catch( System.Threading.ThreadInterruptedException )
{
// And here, if we can
}
finally
{
if( callback != null )
{
callback.End();
}
}
}
 
M

Michael Bray

I am using the following code, what I need to know is, what do I do if I
want to pass parameters to DoSomeWork? I don't understand how the
callback variable is passed to DoSomeWork.

private void SpawnSomeWork()
{
IProgressCallback callback; // = ???
System.Threading.ThreadPool.QueueUserWorkItem(
new System.Threading.WaitCallback(
DoSomeWork ),
callback );
}

private void DoSomeWork( object status )
{

You can change the 'callback' portion of QueueUserWorkItem to an object
array or a custom class, and pass in several parameters, like such:

QueueUserWorkItem(
new WaitCallback(DoSomeWork),
new object[] { callback, param1, param2 }
);

and then parse out the properties in the DoSomeWork function:

private void DoSomeWork( object status )
{
object[] parms = (object[])status;
IProgressCallback callback = (IProgressCallback)parms[0];
int param1 = (int)parms[1];
string param2 = (int)parms[2];
...


-mdb
 
B

Brian Gideon

Mike,

If you're using 2.0 this is super easy. Just use an anonymous method
instead.

private void SpawnSomeWork()
{
object parameter1 = ?;
object parameter2 = ?;
ThreadPool.QueueUserWorkItem(delegate(object state)
{
// Capture local variables.
Console.WriteLine(parameter1);
Console.WriteLine(parameter2);
});
}

Brian
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top