我的代码:
ret.chromeVehicles = _context.Database.SqlQuery<ChromeVehicle>("SELECT Year, Make, Model, ModelNumber, MIN(VIN) as VIN FROM DealerInventory WHERE DealerID = 1 GROUP BY Year, Make, Model, ModelNumber").ToList();
List<Thread> threadList = new List<Thread>();
foreach (ChromeVehicle vehicle in ret.chromeVehicles)
{
var thread = new Thread(delegate () {
// Here is an API call which fills the data variable (this works fine)
foreach (JObject incentive in data["incentives"])
{
// Add finance rate incentives
if ((string)incentive["categoryDescription"] == "Finance Rate")
{
// Add Chrome Incentive to Finance Rate
var inc = new ChromeIncentive();
inc.Group = (string)incentive["groupAffiliation"];
inc.Ownership = (string)incentive["previousOwnership"];
inc.ID = (int)incentive["incentiveID"];
inc.Category = (string)incentive["categoryDescription"];
var rate = new ChromeRate();
rate.Incentive = inc;
vehicle.FinanceRates.Add(rate); // Error is on this line
}
}
});
thread.Start();
}
我得到的错误:
附加信息:未将对象引用设置为对象的实例。
我收到错误的行是vehicle.FinanceRates.Add(rate);
我查了一下这个错误,它说它与创建一个空变量有关。所以我认为车辆必须是空变量,但我不确定它是如何空的,因为数据库中没有空行,而且它直接来自数据库。如果我评论vehicle.FinanceRates.Add(rate);
,那么它可以很好地拉动所有车辆的数据。
知道我的代码中可能导致此错误的错误是什么?也许该线程阻止它编辑线程外的变量?
代码应该做什么:
从数据库中提取唯一车辆列表。循环这些车辆并为不同线程中的每个车辆运行API调用。获取API数据并将其添加到车辆数据中。
我甚至尝试检查是否为null,但仍然收到错误:
if (vehicle != null && rate != null)
{
vehicle.FinanceRates.Add(rate);
}
我认为它与Threads有关但是Threads会导致错误吗?