Cannot access a disposed object : DataContext





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I'm using TCPClient to connect to device and get some data as a strings, then I'm trying to save data to DB and getting




"Cannot access a disposed object" error."




Maybe problem is because I'm trying to save to DB from async callback function?
Please take a look, here are two functions: first one gets network stream, already connected to the device and starts reading data, second one is callback:



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);
}
}









share|improve this question

























  • None of this code shows the actual problem, your repository (sigh) has closed the context

    – Michael Randall
    Jan 4 at 8:11













  • As written here, your method are not really "async". And your code is not usable as is. But yes, if they are called asynchronously and the _repo field is closed/disposed meanwhile, this is your error. My guess is you don't properly handle lifetime for your dbcontext.

    – AFract
    Jan 4 at 8:11













  • find which line causes error. and write on here to get answer from ppl.

    – Arphile
    Jan 4 at 8:12











  • Dig around in here _repo.saveEventsToDB(events); work out why you have closed and disposed the context (somwhere else), this will be your answer

    – Michael Randall
    Jan 4 at 8:17











  • Thing is, if I call _repo.saveEventsToDB(events) from another place of program, for example, like this: [HttpPost("saveone")] public async Task<IActionResult> saveOne(Event newEvent) { var events = new List<Event>(); events.Add(newEvent); await _repo.saveEventsToDB(events); return Ok(events); }' it works. So i think problem is because I call it from callback function.. Any idea what can I do?

    – Денис Пархоменко
    Jan 4 at 10:31




















0















I'm using TCPClient to connect to device and get some data as a strings, then I'm trying to save data to DB and getting




"Cannot access a disposed object" error."




Maybe problem is because I'm trying to save to DB from async callback function?
Please take a look, here are two functions: first one gets network stream, already connected to the device and starts reading data, second one is callback:



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);
}
}









share|improve this question

























  • None of this code shows the actual problem, your repository (sigh) has closed the context

    – Michael Randall
    Jan 4 at 8:11













  • As written here, your method are not really "async". And your code is not usable as is. But yes, if they are called asynchronously and the _repo field is closed/disposed meanwhile, this is your error. My guess is you don't properly handle lifetime for your dbcontext.

    – AFract
    Jan 4 at 8:11













  • find which line causes error. and write on here to get answer from ppl.

    – Arphile
    Jan 4 at 8:12











  • Dig around in here _repo.saveEventsToDB(events); work out why you have closed and disposed the context (somwhere else), this will be your answer

    – Michael Randall
    Jan 4 at 8:17











  • Thing is, if I call _repo.saveEventsToDB(events) from another place of program, for example, like this: [HttpPost("saveone")] public async Task<IActionResult> saveOne(Event newEvent) { var events = new List<Event>(); events.Add(newEvent); await _repo.saveEventsToDB(events); return Ok(events); }' it works. So i think problem is because I call it from callback function.. Any idea what can I do?

    – Денис Пархоменко
    Jan 4 at 10:31
















0












0








0








I'm using TCPClient to connect to device and get some data as a strings, then I'm trying to save data to DB and getting




"Cannot access a disposed object" error."




Maybe problem is because I'm trying to save to DB from async callback function?
Please take a look, here are two functions: first one gets network stream, already connected to the device and starts reading data, second one is callback:



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);
}
}









share|improve this question
















I'm using TCPClient to connect to device and get some data as a strings, then I'm trying to save data to DB and getting




"Cannot access a disposed object" error."




Maybe problem is because I'm trying to save to DB from async callback function?
Please take a look, here are two functions: first one gets network stream, already connected to the device and starts reading data, second one is callback:



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






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 4 at 8:25









Vijunav Vastivch

3,4411724




3,4411724










asked Jan 4 at 8:09









Денис ПархоменкоДенис Пархоменко

113




113













  • None of this code shows the actual problem, your repository (sigh) has closed the context

    – Michael Randall
    Jan 4 at 8:11













  • As written here, your method are not really "async". And your code is not usable as is. But yes, if they are called asynchronously and the _repo field is closed/disposed meanwhile, this is your error. My guess is you don't properly handle lifetime for your dbcontext.

    – AFract
    Jan 4 at 8:11













  • find which line causes error. and write on here to get answer from ppl.

    – Arphile
    Jan 4 at 8:12











  • Dig around in here _repo.saveEventsToDB(events); work out why you have closed and disposed the context (somwhere else), this will be your answer

    – Michael Randall
    Jan 4 at 8:17











  • Thing is, if I call _repo.saveEventsToDB(events) from another place of program, for example, like this: [HttpPost("saveone")] public async Task<IActionResult> saveOne(Event newEvent) { var events = new List<Event>(); events.Add(newEvent); await _repo.saveEventsToDB(events); return Ok(events); }' it works. So i think problem is because I call it from callback function.. Any idea what can I do?

    – Денис Пархоменко
    Jan 4 at 10:31





















  • None of this code shows the actual problem, your repository (sigh) has closed the context

    – Michael Randall
    Jan 4 at 8:11













  • As written here, your method are not really "async". And your code is not usable as is. But yes, if they are called asynchronously and the _repo field is closed/disposed meanwhile, this is your error. My guess is you don't properly handle lifetime for your dbcontext.

    – AFract
    Jan 4 at 8:11













  • find which line causes error. and write on here to get answer from ppl.

    – Arphile
    Jan 4 at 8:12











  • Dig around in here _repo.saveEventsToDB(events); work out why you have closed and disposed the context (somwhere else), this will be your answer

    – Michael Randall
    Jan 4 at 8:17











  • Thing is, if I call _repo.saveEventsToDB(events) from another place of program, for example, like this: [HttpPost("saveone")] public async Task<IActionResult> saveOne(Event newEvent) { var events = new List<Event>(); events.Add(newEvent); await _repo.saveEventsToDB(events); return Ok(events); }' it works. So i think problem is because I call it from callback function.. Any idea what can I do?

    – Денис Пархоменко
    Jan 4 at 10:31



















None of this code shows the actual problem, your repository (sigh) has closed the context

– Michael Randall
Jan 4 at 8:11







None of this code shows the actual problem, your repository (sigh) has closed the context

– Michael Randall
Jan 4 at 8:11















As written here, your method are not really "async". And your code is not usable as is. But yes, if they are called asynchronously and the _repo field is closed/disposed meanwhile, this is your error. My guess is you don't properly handle lifetime for your dbcontext.

– AFract
Jan 4 at 8:11







As written here, your method are not really "async". And your code is not usable as is. But yes, if they are called asynchronously and the _repo field is closed/disposed meanwhile, this is your error. My guess is you don't properly handle lifetime for your dbcontext.

– AFract
Jan 4 at 8:11















find which line causes error. and write on here to get answer from ppl.

– Arphile
Jan 4 at 8:12





find which line causes error. and write on here to get answer from ppl.

– Arphile
Jan 4 at 8:12













Dig around in here _repo.saveEventsToDB(events); work out why you have closed and disposed the context (somwhere else), this will be your answer

– Michael Randall
Jan 4 at 8:17





Dig around in here _repo.saveEventsToDB(events); work out why you have closed and disposed the context (somwhere else), this will be your answer

– Michael Randall
Jan 4 at 8:17













Thing is, if I call _repo.saveEventsToDB(events) from another place of program, for example, like this: [HttpPost("saveone")] public async Task<IActionResult> saveOne(Event newEvent) { var events = new List<Event>(); events.Add(newEvent); await _repo.saveEventsToDB(events); return Ok(events); }' it works. So i think problem is because I call it from callback function.. Any idea what can I do?

– Денис Пархоменко
Jan 4 at 10:31







Thing is, if I call _repo.saveEventsToDB(events) from another place of program, for example, like this: [HttpPost("saveone")] public async Task<IActionResult> saveOne(Event newEvent) { var events = new List<Event>(); events.Add(newEvent); await _repo.saveEventsToDB(events); return Ok(events); }' it works. So i think problem is because I call it from callback function.. Any idea what can I do?

– Денис Пархоменко
Jan 4 at 10:31














1 Answer
1






active

oldest

votes


















0














Finally found a solution!



So problem was that I used DataContext dependancy, which was injected in the controller constructor - and it was disposed after HTTP request was completed.



So solution is to inject dependancy manually in the function itself, which needs access to the database:




  1. Inject scope factory IServiceScopeFactory scopeFactory in the controller constructor.



  2. Add this to my function where I need access to DBcontext:



    using (var scope = _scopeFactory.CreateScope())
    {
    var context = scope.ServiceProvider.GetRequiredService();
    ...
    }








share|improve this answer


























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54035174%2fcannot-access-a-disposed-object-datacontext%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Finally found a solution!



    So problem was that I used DataContext dependancy, which was injected in the controller constructor - and it was disposed after HTTP request was completed.



    So solution is to inject dependancy manually in the function itself, which needs access to the database:




    1. Inject scope factory IServiceScopeFactory scopeFactory in the controller constructor.



    2. Add this to my function where I need access to DBcontext:



      using (var scope = _scopeFactory.CreateScope())
      {
      var context = scope.ServiceProvider.GetRequiredService();
      ...
      }








    share|improve this answer






























      0














      Finally found a solution!



      So problem was that I used DataContext dependancy, which was injected in the controller constructor - and it was disposed after HTTP request was completed.



      So solution is to inject dependancy manually in the function itself, which needs access to the database:




      1. Inject scope factory IServiceScopeFactory scopeFactory in the controller constructor.



      2. Add this to my function where I need access to DBcontext:



        using (var scope = _scopeFactory.CreateScope())
        {
        var context = scope.ServiceProvider.GetRequiredService();
        ...
        }








      share|improve this answer




























        0












        0








        0







        Finally found a solution!



        So problem was that I used DataContext dependancy, which was injected in the controller constructor - and it was disposed after HTTP request was completed.



        So solution is to inject dependancy manually in the function itself, which needs access to the database:




        1. Inject scope factory IServiceScopeFactory scopeFactory in the controller constructor.



        2. Add this to my function where I need access to DBcontext:



          using (var scope = _scopeFactory.CreateScope())
          {
          var context = scope.ServiceProvider.GetRequiredService();
          ...
          }








        share|improve this answer















        Finally found a solution!



        So problem was that I used DataContext dependancy, which was injected in the controller constructor - and it was disposed after HTTP request was completed.



        So solution is to inject dependancy manually in the function itself, which needs access to the database:




        1. Inject scope factory IServiceScopeFactory scopeFactory in the controller constructor.



        2. Add this to my function where I need access to DBcontext:



          using (var scope = _scopeFactory.CreateScope())
          {
          var context = scope.ServiceProvider.GetRequiredService();
          ...
          }









        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Feb 5 at 9:41

























        answered Feb 4 at 9:33









        Денис ПархоменкоДенис Пархоменко

        113




        113
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54035174%2fcannot-access-a-disposed-object-datacontext%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Mossoró

            Monofisismo