Created
August 21, 2012 03:15
-
-
Save bradwilson/3411200 to your computer and use it in GitHub Desktop.
Alternate implementation of WriteToStreamAsync
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.