amibar/SmartThreadPool

Null reference exception on IsWorkItemCanceled call

UweKeim opened this issue · 3 comments

I've ugraded from using an older version of STP to the newest one available on NuGet.

Now I get an error:

System.NullReferenceException

With the following stack trace (excerpt):

at Amib.Threading.SmartThreadPool.get_IsWorkItemCanceled() in e:\Dev\STP\STP.git\SmartThreadPool\SmartThreadPool.cs:Zeile 1420.
at ZetaTest.Runtime.Code.ThreadPooling.ThreadPoolManager.CheckWantCancel() in C:\P\Zeta Test\3.5\Zeta Test Main\Source\Runtime\Code\ThreadPooling\ThreadPoolManager.cs:Zeile 260.
at ...

It seems that the line number 140 is different from the code in this GitHub repository, since the function IsWorkItemCanceled seems to be located here.

My question:

Am I doing anything wrong to get the null reference exception?

@UweKeim, this property only works from the work item callback.

Thanks a lot.

Strange that my code stops working with the newest version and seemed to work before.

I'll put a if ( Thread.CurrentThread.IsBackground ) check before calling your function.

I hope this is sufficient.

I guess Thread.CurrentThread.IsThreadPoolThread will not return true, since you do not use the built-in thread pool?!

Just for the records, I ended up writing this helper method:

public static bool IsWorkItemCanceled()
{
    var cte =
        typeof(SmartThreadPool)
            .GetProperty(@"CurrentThreadEntry", BindingFlags.NonPublic | BindingFlags.Static)
            .GetValue(null);
    var cwe = cte?.GetType().GetProperty(@"CurrentWorkItem").GetValue(cte) as WorkItem;
    return cwe != null && cwe.IsCanceled;
}

An alternative way would be:

public static bool IsWorkItemCanceled()
{
    return Thread.CurrentThread.IsBackground &&
           !Thread.CurrentThread.IsThreadPoolThread /*the classic one!*/ &&
           SmartThreadPool.IsWorkItemCanceled;
}

I hope this helps other users, too.