无法访问已释放的对象:DataContext的

问题描述 投票:0回答:1

我使用TCPClient连接到设备,并得到一些数据作为一个字符串,然后我试图将数据保存到数据库并获得

“无法访问已释放的对象”错误“。

也许问题是因为我想保存到数据库从异步回调函数?请看看,这里有两个功能:第一个获取网络数据流,已连接到设备,并开始读取数据,第二个是回调:

private void ReadDataAsync(NetworkStream nwStream)
        {
            byte[] buffer = new byte[1024];

            messageStream mStream = new messageStream(nwStream, buffer);

            if (nwStream.CanRead)
            {
                Console.WriteLine("Starting async");
                nwStream.BeginRead(buffer, 0, buffer.Length,
                    new AsyncCallback(OnReadEndAsync), mStream);
            }

            else
            {
                Console.WriteLine("Cannot read stream");
            }
        }

        private void OnReadEndAsync(IAsyncResult result)
        {
            String message = "";

            messageStream mStream = (messageStream)result.AsyncState;
            int incDataSize = mStream.nwStream.EndRead(result);

            message = Encoding.ASCII.GetString(mStream.buffer, 0, incDataSize);
            List<Event> events = new List<Event>();
            events = ProcessMessage(message);
            if(events.Any())
                 _repo.saveEventsToDB(events);
            if (mStream.nwStream.CanRead)
            {
                mStream.nwStream.BeginRead(mStream.buffer, 0, mStream.buffer.Length,
                    new AsyncCallback(OnReadEndAsync), mStream);
            }
        }
c# .net tcpclient beginread
1个回答
0
投票

终于找到了解决办法!

所以问题是,我使用的DataContext扶养,这是在所述控制器构造注入 - 和HTTP请求完成后,这是设置。

所以,解决办法是在函数中,需要访问数据库手动进依赖性:

  1. 注射范围厂IServiceScopeFactory scopeFactory控制器构造。
  2. 这添加到我的功能,我需要访问的DbContext: 使用(品种范围= _scopeFactory.CreateScope()){风险上下文= scope.ServiceProvider.GetRequiredService(); ...}
© www.soinside.com 2019 - 2024. All rights reserved.