I have a routine which is called upon a background worker completing. As below;
private void BatteryListFetchBackgroundWorkerRunWorkerCompleter(object sender, RunWorkerCompletedEventArgs e)
{
this.Cursor = Cursors.Default;
var sortedList = this.currentBatteries.Values.OrderBy(g => g, new BatteryNameComparer()); //breaks here
this.BatteryBindingSource.DataSource = sortedList;
if (this.batteryListBox.Items.Count > 0)
{
this.batteryListBox.SetSelected(0, true);
}
this.viewScheduleButton.Enabled = true;
this.viewDefaultScheduleButton.Enabled = true;
this.viewEditScheduleLimits.Enabled = true;
}
The line it's breaking at is;
this.BatteryBindingSource.DataSource = sortedList;
The exception is null reference exception and it occurs when setting the data source
The code for BatteryNameComparer
public class BatteryNameComparer : IComparer<Battery>
{
/// <summary>
/// Compares DDSMGroup
/// </summary>
/// <param name="a">first value for comparison</param>
/// <param name="b">second value for comparison</param>
/// <returns>An integer indicating the compare result</returns>
public int Compare(Battery a, Battery b)
{
int aId = int.Parse(a.DeviceName.Substring(BatteryOverviewControl.BatteryPrefixSubstring.Length));
int bId = int.Parse(b.DeviceName.Substring(BatteryOverviewControl.BatteryPrefixSubstring.Length));
return aId.CompareTo(bId);
}
}
Whenever you see a
TargetInvocationException
, you should immediately inspect itsInnerException
property to find the exception that was actually thrown.http://msdn.microsoft.com/en-us/library/system.exception.innerexception(v=vs.110).aspx
Simply put, a
TargetInvocationException
tells you only that another exception was thrown within some sort of invocation context - this is nearly always a cross thread operation or call via reflection.