Skip to content

Instantly share code, notes, and snippets.

@bradwilson
Created August 21, 2012 03:15
Show Gist options
  • Save bradwilson/3411200 to your computer and use it in GitHub Desktop.
Save bradwilson/3411200 to your computer and use it in GitHub Desktop.
Alternate implementation of WriteToStreamAsync
public override Task WriteToStreamAsync(Type type, object value,
Stream stream,
HttpContent content,
TransportContext transportContext)
{
if (string.IsNullOrEmpty(JsonpCallbackFunction))
return base.WriteToStreamAsync(type, value, stream, content, transportContext);
StreamWriter writer = null;
try
{
writer = new StreamWriter(stream);
writer.Write(JsonpCallbackFunction + "(");
writer.Flush();
}
catch(Exception ex)
{
try
{
if (writer != null)
writer.Dispose();
}
catch { }
var tcs = new TaskCompletionSource<object>();
tcs.SetException(ex);
return tcs.Task;
}
return base.WriteToStreamAsync(type, value, stream, content, transportContext)
.ContinueWith(innerTask =>
{
if (innerTask.Status == TaskStatus.RanToCompletion)
{
writer.Write(")");
writer.Flush();
}
return innerTask;
}, TaskContinuationOptions.RunSynchronously)
.Unwrap()
.ContinueWith(innerTask =>
{
writer.Dispose();
return innerTask;
}, TaskContinuationOptions.RunSynchronously)
.Unwrap();
}
public override async Task WriteToStreamAsync(Type type, object value,
Stream stream,
HttpContent content,
TransportContext transportContext)
{
if (string.IsNullOrEmpty(JsonpCallbackFunction))
{
await base.WriteToStreamAsync(type, value, stream, content, transportContext);
return;
}
using (var writer = new StreamWriter(stream))
{
writer.Write(JsonpCallbackFunction + "(");
writer.Flush();
await base.WriteToStreamAsync(type, value, stream, content, transportContext);
writer.Write(")");
writer.Flush();
}
}
@RickStrahl
Copy link

Brad, in the .NET 4.0 code what's the reason for the two ContinueWith() blocks on the bottom breaking up the write and close operation especially since the code in those async operations is marked as executeSynchronous.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment