Using threadpool and func objects

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

I don't see func that takes one parameter but returns nothing. There is func<T, TResult>

, but how can I set TResult to null (want to say "this method returns void")?

Also, how can I use threadpool for methods that return and accept all kinds of parameters? Can I not store Func objects in a shared collection as well as int to indicate priority and then execute those functions?

Finally, in a static object (like a collection), what kind of synchronization is needed in the global application?

+1


source to share


1 answer


The only delegate Func<...>

/ Action<...>

that looks like WaitCallback

is Action<object>

. It will not be used directly; however, you can wrap delegates inside eachother:

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

      

To return the result, you need to update the external state. Lambdas / anon methods are good for this as they offer closure support:

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

      

Once executed, result

(from the above context) will update. However, the 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);
        });

      

If the callback function does something useful with the result.

Hopefully this also shows how you can execute arbitrary functions on a thread pool thread.

Re-sync; you are on a secondary thread, so you will definitely need sync if you are talking to any shared state. However, you can use the UI to sync the result (if appropriate) - that is (from winform):

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

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

});

      

+2


source







All Articles