Async network operations never finish

So i’ve made an extension method on IDisposable that creates a CancellationToken that disposes the connection on timeout, so the task finishes and everything carries on: public static IDisposable CreateTimeoutScope(this IDisposable disposable, TimeSpan timeSpan) { var cancellationTokenSource = new CancellationTokenSource(timeSpan); var cancellationTokenRegistration = cancellationTokenSource.Token.Register(disposable.Dispose); return new DisposableScope( () => { cancellationTokenRegistration.Dispose(); cancellationTokenSource.Dispose(); disposable.Dispose(); }); } … Read more

How do I dispose my filestream when implementing a file download in ASP.NET?

You don’t need to dispose the stream. It will be disposed by the FileStreamResult.WriteFile method. Code excerpt from this class: public FileStreamResult(Stream fileStream, string contentType) : base(contentType) { if (fileStream == null) { throw new ArgumentNullException(“fileStream”); } this.FileStream = fileStream; } protected override void WriteFile(HttpResponseBase response) { Stream outputStream = response.OutputStream; using (this.FileStream) { byte[] … Read more

Should you implement IDisposable.Dispose() so that it never throws?

The Framework Design Guidelines (2nd ed) has this as (ยง9.4.1): AVOID throwing an exception from within Dispose(bool) except under critical situations where the containing process has been corrupted (leaks, inconsistent shared state, etc.). Commentary [Edit]: There are guidelines, not hard rules. And this is an “AVOID” not a “DO NOT” guideline. As noted (in comments) … Read more

Should I call Close() or Dispose() for stream objects?

A quick jump into Reflector.NET shows that the Close() method on StreamWriter is: public override void Close() { this.Dispose(true); GC.SuppressFinalize(this); } And StreamReader is: public override void Close() { this.Dispose(true); } The Dispose(bool disposing) override in StreamReader is: protected override void Dispose(bool disposing) { try { if ((this.Closable && disposing) && (this.stream != null)) { … Read more