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;
}
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
|
show 2 more comments
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
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
|
show 2 more comments
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
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
c# .net tcpclient beginread
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
|
show 2 more comments
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
|
show 2 more comments
1 Answer
1
active
oldest
votes
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:
Inject scope factory IServiceScopeFactory scopeFactory in the controller constructor.
Add this to my function where I need access to DBcontext:
using (var scope = _scopeFactory.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService();
...
}
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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:
Inject scope factory IServiceScopeFactory scopeFactory in the controller constructor.
Add this to my function where I need access to DBcontext:
using (var scope = _scopeFactory.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService();
...
}
add a comment |
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:
Inject scope factory IServiceScopeFactory scopeFactory in the controller constructor.
Add this to my function where I need access to DBcontext:
using (var scope = _scopeFactory.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService();
...
}
add a comment |
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:
Inject scope factory IServiceScopeFactory scopeFactory in the controller constructor.
Add this to my function where I need access to DBcontext:
using (var scope = _scopeFactory.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService();
...
}
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:
Inject scope factory IServiceScopeFactory scopeFactory in the controller constructor.
Add this to my function where I need access to DBcontext:
using (var scope = _scopeFactory.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService();
...
}
edited Feb 5 at 9:41
answered Feb 4 at 9:33


Денис ПархоменкоДенис Пархоменко
113
113
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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