小编Jam*_*van的帖子

无法理解为什么我得到NullReferenceException

我有一个代码块,它从队列中读取,处理一个项目(在自己的线程中),然后重复直到队列为空.

public ActionResult GetOrdersAsync() {

        int count = 0;
        SyncDM sync = _common.StartSync();

        while (sync != null && sync.SyncId != 0) {

            int customerId;
            bool result = int.TryParse(sync.Payload, out customerId);
            if (result) {
                Task.Run(() => GetOrders(sync.SyncId, customerId));
            }

            count++;
            //Process the next Sync
            sync = _common.StartSync();

        }

        return Json(new JsonModel {
            Message = "Started " + count + " instances of GetOrders",
            Success = count > 0
        });

    }
Run Code Online (Sandbox Code Playgroud)

StartSync()要么从队列中删除项目,要么在队列为空时返回null.GetOrders()处理对象.

问题是有时代码在此行引发NullReferenceException Task.Run(()=> GetOrders(sync.SyncId,customerId));

在调试器中,Sync是null(异常的原因),但customerId有一个值.这告诉我同步在前一行有一个值.这让我感到困惑,我认为它与Task.Run和线程有关,但我不明白本地范围的变量如何自发地改变它的值.

c# multithreading nullreferenceexception

3
推荐指数
1
解决办法
88
查看次数