Search code examples
c#threadpoolargumentnullexceptionqueueuserworkitem

AgrumenNullException in ThreadPool.QueueUserWorkItem


I've got a method which gets called frequently by different treads. Sometimes I get an AgrumenNullException when ThreadPool.QueueUserWorkItem(display(angebot), null); gets called, stating that the parameter callBack (the first parameter) is null.

What am I doing wrong?


public class ai : UserControl
{
    //...
    public void Display(Angebote angebot)
    {
        lock (_syncObj) { _current = angebot; }
        ThreadPool.QueueUserWorkItem(display(angebot), null);
    }
    private WaitCallback display(Angebote angebot)
    {
        // doing something
    }
    //...
}

Solution

  • The ThreadPool.QueueUserWorkItem will do the work as defined in the WaitCallback delegate returned by display(Angebote). I would surmise that your display method sometimes returns null.

    Is your intent to execute display(angebot) in the background thread, or does that method discern what method should be executed?

    If you're thinking that your display method should be executing in a background thread:

    private WaitCallback display(Angebote angebot)
    {
        // doing something in a background thread
    }
    

    Then your code should look like:

    ThreadPool.QueueUserWorkItem(display, angebot);
    
    private void display(object state)
    {
        Angebot angebot = (Angebot)state;
        // doing something in a background thread
    }
    

    EDIT: If it's the latter where display is figuring out what background thread to execute, then perhaps you have something looking like this:

    private WaitCallback display(Angebote angebot)
    {
        if (angebot.Something)
        {
             return new WaitCallback(BackgroundTask1);
        }
        else
        {
            return null;
        }
    }
    

    But since you haven't posted that code, I'm not sure. In this case, returning null is invalid for ThreadPool.QueueUserWorkItem.