1

When using a thread pool and its queuecallbackitem, can I not pass in a func object (from the method parameter)?

I don't see a func which takes one parameter but returns nothing. There isfunc<T, TResult> but how can I set TResult to be null (want to indicate "this method returns void")?

Also, how could I use the threadpool for methods which return and take all sorts of paremeters? Could I not store Func objects in a generic collection and also an int to indicate priority, then execute those funcs?

Finally, in a static object (such as collection), what synchronisation in a global application would it need?

1 Answer 1

3

The only Func<...>/Action<...> delegate that is similar to WaitCallback is Action<object>. It won't be directly usable; however, you can wrap delegates inside eachother:

        Action<object> func = // TODO
        ThreadPool.QueueUserWorkItem(state=>func(state));   

To return a result, one option is to update external state. Lambdas / anon-methods are good for this, since they offer closure support:

        Func<int, int> func = x => x * 5;
        int query = 4, result = 0;
        ThreadPool.QueueUserWorkItem(state=> {
            result = func(query);
        });

After execution, result (from the above context) will be updated. However, a callback is more common:

        Func<int, int> func = x => x * 5;
        int query = 4;
        Action<int> callback = x =>
        {
            Console.WriteLine(x);
        };
        ThreadPool.QueueUserWorkItem(state=> {
            int result = func(query);
            callback(result);
        });

Where the callback function does something useful with the result.

Hopefully that also shows how you can execute arbitrary functions in a thread-pool thread.

Re synchronization; you are on a secondary thread, so you definitely would need synchronization if talking to any shared state. However, you might choose to use the UI to synchronize the result (if suitable) - i.e. (from a winform):

ThreadPool.QueueUserWorkItem(state => {
    // now on worker thread
    int result = ... // TODO

    this.Invoke((Action)delegate {
       // now on UI thread
       this.Text = result.ToString();
    });

});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.