today i was faced with a very strange error regarding Tasks. In my code i tried to use the using
statement this way:
protected MyClass() {
using(var initTask = new Task(() => Init())) {
initTask.ContinueWith(result => InitCompletedCallBack(result));
initTask.Start();
}
}
protected virtual void Init() {}
private void InitCompletedCallBack(AsyncResult result) {
// Stuff
}
When i execute this code i get an Task_Dispose_NotComplete error. The error occures when InitCompletedCallBack has finished.
While trying arounf i changed the using to this:
using(var initTask = new Task(() => Init())) {
initTask.ContinueWith(result => InitCompletedCallBack(result));
initTask.Start();
Thread.Sleep(1000);
}
And that worked. However, this piece of code will be executed several times when the application starts and thus freezes the application for approximatelly 15-20 seconds. But it shows that something (inside the task?) needs at least one second to finish.
Any ideas what causes this behavior?
Thanks in advance.
Edit When i set the time to wait to 100ms, the error occures. The first lines of the StackTrace are:
bei System.Threading.Tasks.Task.Dispose(Boolean disposing)
bei System.Threading.Tasks.Task.Dispose()
bei MyClass..ctor() in c:\Path\to\source\MyClass.cs:line 33.
Line 33 is the closing bracket of the using block.
Any ideas what causes this behavior?
Your code causes this behavior. You dispose a task that is not yet done. Why do you want to dispose it where you dispose it? Does the using-block make sense where you put it?
Do not dispose a task that you still rely on. Remove the using block.