I’m trying to turn a stored procedure call, within a data method, to an async call. This is the original method:
public void InsertFoo(Foo foo)
{
this.Database.SomeStoredProcedure(foo);
}
My first attempt was this:
public void InsertFoo(Foo foo)
{
Task.Factory.StartNew(() =>
{
this.Database.SomeStoredProcedure(foo);
});
}
However, I get a runtime error that this.Database is null. (this.Database is the L2S data context.)
Then I did some research and thought creating my own local copy would do it:
public void InsertFoo(Foo foo)
{
MyDataContext db = this.Database;
Task.Factory.StartNew(() =>
{
db.SomeStoredProcedure(foo);
});
}
However, db is disposed before it actually gets used by the thread, resulting in another runtime error.
I simply want to pass this.Database into the threaded method. Is that possible? If so, how? this.Database is going to be destroyed when the method returns, because the class instance is gone, so I’m not sure how to solve this.
Bob. As the InsertFoo method returns immediately, the containing object instance is available for collection, and hence when the calls is made to the database the database instance has been disposed.
e.g. If you are doing something like
Then your FooContainer will dispose before the async call within the foo method has executed.
I think you’d be better off calling InsertFoo asynchronously rather that making an async call from within that method.
e.g. Something on the lines of
Task.Factory.StartNew(()=> xx.InsertFoo(foo))and using a continuation on completion to tidy up yourxxcontaining object.