I'm working on a project where we would like to send messages via an Azure Service Bus (Topic). In this instance, I've setup a C# Console app and a Java app that sends and receives messages between them.
When sending a message from C#, I get a strangely formatted string within Java containing "schema.microsoft.com/2003/10/serialisation". Changing the message content type makes no difference.
When sending data from Java to C# I get an exception.
Send/Receive Data - C#
private static void SendMessages()
{
topicClient = TopicClient.Create(TopicName);
List<BrokeredMessage> messageList = new List<BrokeredMessage>();
messageList.Add(CreateSampleMessage("1", "Test"));
Console.WriteLine("\nSending messages to topic...");
foreach (BrokeredMessage message in messageList)
{
while (true)
{
try
{
topicClient.Send(message);
}
catch (MessagingException e)
{
if (!e.IsTransient)
{
Console.WriteLine(e.Message);
throw;
}
else
{
HandleTransientErrors(e);
}
}
Console.WriteLine(string.Format("Message sent: Id = {0}, Body = {1}", message.MessageId, message.GetBody<string>()));
break;
}
}
topicClient.Close();
}
private static BrokeredMessage CreateSampleMessage(string messageId, string messageBody)
{
BrokeredMessage message = new BrokeredMessage(messageBody);
message.MessageId = messageId;
return message;
}
C# Stacktrace
{"There was an error deserializing the object of type System.String. Unexpected end of file. Following elements are not closed: ."}
at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.DataContractSerializer.ReadObject(XmlDictionaryReader reader, Boolean verifyObjectName)
at Microsoft.ServiceBus.Messaging.DataContractBinarySerializer.ReadObject(XmlDictionaryReader reader, Boolean verifyObjectName)
at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.XmlObjectSerializer.ReadObject(XmlDictionaryReader reader)
at Microsoft.ServiceBus.Messaging.DataContractBinarySerializer.ReadObject(Stream stream)
at Microsoft.ServiceBus.Messaging.BrokeredMessage.GetBody[T](XmlObjectSerializer serializer)
at Microsoft.ServiceBus.Messaging.BrokeredMessage.GetBody[T]()
at Microsoft.Samples.MessagingWithTopics.program.ReceiveMessages() in d:\Downloads\Getting Started Messaging With Topics (1)\C#\MessagingWithTopics\program.cs:line 127
at Microsoft.Samples.MessagingWithTopics.program.Main(String[] args) in d:\Downloads\Getting Started Messaging With Topics (1)\C#\MessagingWithTopics\program.cs:line 39
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
a) You may not use AMQP from .NET. Only then you get AMQP encoding. Append TransportType=Amqp to connection string. And then use Apache Proton-J's JMS provider.
b) If you use HTTP from Java, try constructing the message either over a self-serialized stream (Stream parameterized constructor) or using for instance the DataContractSerializer explicity with the (object, XmlObjectSerializer) parameterized constructor. That will give you an XML Test payload. By default we use the NetDataContractSerializer which yields a compact encoding but is .NET only.
Related
Using the following code snippet in WinForms, I am successfully able to upload documents through a REST API. But as soon as I move to ASP.NET, it throws a NullReferenceException.
public async Task<string> TestUpload()
{
const string cServerBaseAddress = "https://test-testrestservice.abcd.com/";
const string cFilename = #"D:\temp\Test.txt";
const string cUrl = "{0}abc/dms/api/v1/crmdocuments/?BusinessUnit={1}&AccountID={2}&DocumentType={3}&Description={4}&Filename={5}";
string businessUnit = "XYZ";
string accountID = "ABCCompany";
string docType = "Affidavit";
string description = #"\%&description&%/";
string responseContent = string.Empty;
try
{
string url = string.Format(cUrl, cServerBaseAddress,
WebUtility.UrlEncode(businessUnit), WebUtility.UrlEncode(accountID),
WebUtility.UrlEncode(docType), WebUtility.UrlEncode(description),
WebUtility.UrlEncode(Path.GetFileName(cFilename)));
using (HttpClient client = GetClient(cServerBaseAddress))
{
using (HttpResponseMessage response = await client.PostAsync(url, new ByteArrayContent(File.ReadAllBytes(cFilename))))
{
responseContent = await response.Content.ReadAsStringAsync();
response.EnsureSuccessStatusCode();
string newContentId = Newtonsoft.Json.Linq.JToken.Parse(response.Content.ReadAsStringAsync().Result).ToString();
return newContentId;
}
}
}
I've debugged the client, url, and ByteArrayContent, and none of them is null. But I am still getting an unhandled exception.
Here are the details of the exception:
at System.Web.ThreadContext.AssociateWithCurrentThread(Boolean setImpersonationContext)
at System.Web.HttpApplication.OnThreadEnterPrivate(Boolean setImpersonationContext)
at System.Web.LegacyAspNetSynchronizationContext.CallCallbackPossiblyUnderLock(SendOrPostCallback callback, Object state)
at System.Web.LegacyAspNetSynchronizationContext.CallCallback(SendOrPostCallback callback, Object state)
at System.Web.LegacyAspNetSynchronizationContext.Post(SendOrPostCallback callback, Object state)
at System.Threading.Tasks.SynchronizationContextAwaitTaskContinuation.PostAction(Object state)
at System.Threading.Tasks.AwaitTaskContinuation.RunCallback(ContextCallback callback, Object state, Task& currentTask)
--- End of stack trace from previous location where exception was thrown ---
at System.Threading.Tasks.AwaitTaskContinuation.<>c.<ThrowAsyncIfNecessary>b__18_0(Object s)
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
The presence of "LegacyAspNetSynchronizationContext" in your stack trace is a clue as to what's wrong.
If you want to use await in ASP.NET 4.5, then you must add the following element in Web.config:
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
From the documentation (emphasis added):
Setting this compatibility switch is mandatory for WebSockets-enabled applications, for using Task-based asynchrony in Web Forms pages, and for certain other asynchronous behaviors.
UPDATE: If you want to call an async method from a non-async method, and you don't care about the result, then one way to do so is to use Task.Run:
Task.Run(() => TestUpload());
I'm trying to download a zip file in Windows Application , but is is throwing an error . My code is :
string url = "https://www.nseindia.com/content/historical/DERIVATIVES/2017/JUN/fo07JUN2017bhav.csv.zip";
using (WebClient wc = new WebClient())
{
wc.DownloadFile(url, #"c:\bhav\file.zip");
}
Exception details :
System.Net.WebException was unhandled HResult=-2146233079
Message=The remote server returned an error: (403) Forbidden.
Source=System StackTrace:
at System.Net.WebClient.DownloadFile(Uri address, String fileName)
at System.Net.WebClient.DownloadFile(String address, String fileName)
at unzip.Form1.downloadFile() in c:\users\ethicpro\documents\visual studio
2015\Projects\unzip\unzip\Form1.cs:line 30
at unzip.Form1..ctor() in c:\users\ethicpro\documents\visual studio 2015\Projects\unzip\unzip\Form1.cs:line 20
at unzip.Program.Main() in c:\users\ethicpro\documents\visual studio 2015\Projects\unzip\unzip\Program.cs:line 19
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
at System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()
at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext
activationContext, String[] activationCustomData)
at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext
activationContext)
at System.Activator.CreateInstance(ActivationContext activationContext)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart() InnerException:
Link is : https://www.nseindia.com/content/historical/DERIVATIVES/2017/JUN/fo07JUN2017bhav.csv.zip
I searched for other questions but didn't get the proper answer.
Try this
string url = "https://www.nseindia.com/content/historical/DERIVATIVES/2017/JUN/fo07JUN2017bhav.csv.zip";
string fileName = #"C:\Temp\tt.zip";
using (WebClient wc = new WebClient())
{
wc.Headers.Add("User-Agent: Other");
wc.DownloadFile(url, fileName);
}
The file might no longer exist.
I use VB.Net.
But you have to use the equivalent of on error resume next on this file or another file with a more recent date with and without on error resume next. Or the equivalent in C#.
Another option is that some characters cannot be downloaded, like : | > or .csv.zip should be .zip without the .csv.
In my company we are using SimpleInjector as our IoC framework and are now looking at using Rebus as a wrapper for sending messages via RabbitMq. I am looking for help in creating a working example. I have tried the following code:
using Rebus.Activation;
using Rebus.Config;
using Rebus.Handlers;
using Rebus.Pipeline;
using Rebus.RabbitMq;
using Rebus.SimpleInjector;
using SimpleInjector;
using System;
using System.Threading.Tasks;
namespace SearchType.ProjectionA
{
class Program
{
static void Main(string[] args)
{
var container = new Container();
container.Register<IContainerAdapter, SimpleInjectorContainerAdapter>();
container.Register<IHandleMessages<string>, Handler>();
var adapter = container.GetInstance<IContainerAdapter>();
var bus = Configure.With(adapter)
.Logging(l => l.ColoredConsole())
.Transport(t => t.UseRabbitMq("amqp://localhost", "simpleinjector_consumer"))
.Start();
bus.Subscribe<string>().Wait();
Console.WriteLine("Projection A listening - press ENTER to quit");
Console.ReadLine();
}
}
public class Handler : IHandleMessages<string>
{
public Task Handle(string message)
{
return Task.Run(() =>
{
Console.WriteLine(string.Format("{0} - {1}", MessageContext.Current.Message.Headers["rbs2-corr-id"], message));
});
}
}
}
When i try and run this console application I am getting the following error:
System.InvalidOperationException was unhandled
HResult=-2146233079
Message=The container can't be changed after the first call to GetInstance, GetAllInstances and Verify. The following stack trace describes the location where the container was locked:
at SearchType.ProjectionA.Program.Main(String[] args) in C:\HRG\TravTech\Springboard\SearchType\SearchType.ProjectionA\Program.cs:line 34
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
Source=SimpleInjector
StackTrace:
at SimpleInjector.Container.ThrowWhenContainerIsLocked()
at SimpleInjector.Container.AddRegistration(Type serviceType, Registration registration)
at SimpleInjector.Container.RegisterSingleton[TService](TService instance)
at Rebus.SimpleInjector.SimpleInjectorContainerAdapter.SetBus(IBus bus)
at Rebus.Config.RebusConfigurer.Start()
at SearchType.ProjectionA.Program.Main(String[] args) in C:\HRG\TravTech\Springboard\SearchType\SearchType.ProjectionA\Program.cs:line 36
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
Does anyone know what I can do to fix this? I don't want to have to declare all the dependencies myself.
Edit: thank you Steven for your reply. I have changed the code according to your answer and am now getting a different error.
System.InvalidOperationException was unhandled
HResult=-2146233079
Message=The configuration is invalid. Creating the instance for type IMessageContext failed. The registered delegate for type IMessageContext threw an exception. Attempted to inject the current message context from MessageContext.Current, but it was null! Did you attempt to resolve IMessageContext from outside of a Rebus message handler?
Source=SimpleInjector
StackTrace:
at SimpleInjector.InstanceProducer.VerifyInstanceCreation()
at SimpleInjector.Container.VerifyInstanceCreation(InstanceProducer[] producersToVerify)
at SimpleInjector.Container.VerifyThatAllRootObjectsCanBeCreated()
at SimpleInjector.Container.VerifyInternal(Boolean suppressLifestyleMismatchVerification)
at SimpleInjector.Container.Verify()
at SearchType.ProjectionA.Program.Main(String[] args) in C:\HRG\TravTech\Springboard\SearchType\SearchType.ProjectionA\Program.cs:line 27
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
HResult=-2146233088
Message=The registered delegate for type IMessageContext threw an exception. Attempted to inject the current message context from MessageContext.Current, but it was null! Did you attempt to resolve IMessageContext from outside of a Rebus message handler?
Source=SimpleInjector
StackTrace:
at SimpleInjector.InstanceProducer.GetInstance()
at SimpleInjector.InstanceProducer.VerifyInstanceCreation()
InnerException:
HResult=-2146233079
Message=Attempted to inject the current message context from MessageContext.Current, but it was null! Did you attempt to resolve IMessageContext from outside of a Rebus message handler?
Source=Rebus.SimpleInjector
StackTrace:
at Rebus.SimpleInjector.SimpleInjectorContainerAdapter.<SetBus>b__7()
at lambda_method(Closure )
at SimpleInjector.InstanceProducer.BuildAndReplaceInstanceCreatorAndCreateFirstInstance()
at SimpleInjector.InstanceProducer.GetInstance()
InnerException:
The error indicates that IMessageContext can only be instantiated inside a message handler. Is there a way to ignore certain errors?
I think the exception is clear; Simple Injector prevents registration after you already resolved. Reasons for doing this are described here.
The solution is to manually create the SimpleInjectorContainerAdapter and prevent relying on the container's auto-wiring capability for the adapter:
var container = new Container();
IContainerAdapter adapter = new SimpleInjectorContainerAdapter(container);
container.Register<IHandleMessages<string>, Handler>();
var bus = Configure.With(adapter)
.Logging(l => l.ColoredConsole())
.Transport(t => t.UseRabbitMq("amqp://localhost", "simpleinjector_consumer"))
.Start();
container.Verify();
I'm trying to get a html page content from a private service.
The page returns status code 0, which is not valid. But the page do render when browsing through a browser.
When I try use WebResponse.GetResponseStream() it simply returns empty stream.
And when I try use HttpClient.GetStringAsync(url).Result, it throws AggregateException as follow:
System.AggregateException was unhandled
HResult=-2146233088
Message=One or more errors occurred.
Source=mscorlib
StackTrace:
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task`1.get_Result()
at DiagnosticInfoCrawler.Program.Main(String[] args) in c:\TFS\MSNMetro\Tools\Verticals\Sports\DiagnosticInfoCrawler\Program.cs:line 47
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.Net.Http.HttpRequestException
HResult=-2146233088
Message=Response status code does not indicate success: 0 ().
InnerException:
Two types of code used as follow:
WebResponse response = GetWebResponse(url);
responseBody = (new StreamReader(response.GetResponseStream())).ReadToEnd();
HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(url);
pageSource = httpClient.GetStringAsync(url).Result;
Anyone can advise how can I get the response body? (given that I have no control to fix the service to return the correct status code.)
Thank you,
DD
Catch WebException to get the response. This is a poor design decision by Microsoft since non 200 codes can be part of the normal case.
try
{
WebResponse response = GetWebResponse(url);
responseBody = (new StreamReader(response.GetResponseStream())).ReadToEnd();
HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(url);
pageSource = httpClient.GetStringAsync(url).Result;
}
catch (WebException exception)
{
var response = (HttpWebResponse)exception.GetResponse();
//the response is here..
}
Didn't resolve this issue directly, but instead went to the approach to use TcpClient to read the response.
I've noticed that when I'm using System.Net.HttpClient with a short timeout, it may sometimes crash the process, even when it is wrapped in a try-catch block. Here's a short program to reproduce this.
public static void Main(string[] args)
{
var tasks = new List<Task>();
for (int i = 0; i < 1000; i++)
{
tasks.Add(MakeHttpClientRequest());
}
Task.WaitAll(tasks.ToArray());
}
private async static Task MakeHttpClientRequest()
{
var httpClient = new HttpClient { Timeout = TimeSpan.FromMilliseconds(1) };
var request = "whatever";
try
{
HttpResponseMessage result =
await httpClient.PostAsync("http://www.flickr.com/services/rest/?method=flickr.test.echo&format=json&api_key=766c0ac7802d55314fa980727f747710",
new StringContent(request));
await result.Content.ReadAsStringAsync();
}
catch (Exception x)
{
Console.WriteLine("Error occurred but it is swallowed: " + x);
}
}
Running this will crash the process with the following exception:
Unhandled Exception: System.AggregateException: One or more errors occurred. ---> System.Net.WebException: The request was canceled
at System.Net.ServicePointManager.FindServicePoint(Uri address, IWebProxy proxy, ProxyChain& chain, HttpAbortDelegate& abortDelegate, Int32& abortState)
at System.Net.HttpWebRequest.FindServicePoint(Boolean forceFind)
at System.Net.HttpWebRequest.get_ServicePoint()
at System.Net.AuthenticationState.PrepareState(HttpWebRequest httpWebRequest)
at System.Net.AuthenticationState.ClearSession(HttpWebRequest httpWebRequest)
at System.Net.HttpWebRequest.ClearAuthenticatedConnectionResources()
at System.Net.HttpWebRequest.Abort(Exception exception, Int32 abortState)
at System.Net.HttpWebRequest.Abort()
at System.Net.Http.HttpClientHandler.OnCancel(Object state)
at System.Threading.CancellationCallbackInfo.ExecutionContextCallback(Object obj)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.CancellationCallbackInfo.ExecuteCallback()
at System.Threading.CancellationTokenSource.CancellationCallbackCoreWork(CancellationCallbackCoreWorkArguments args)
at System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(Boolean throwOnFirstException)
--- End of inner exception stack trace ---
at System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(Boolean throwOnFirstException)
at System.Threading.CancellationTokenSource.NotifyCancellation(Boolean throwOnFirstException)
at System.Threading.CancellationTokenSource.TimerCallbackLogic(Object obj)
at System.Threading.TimerQueueTimer.CallCallbackInContext(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.TimerQueueTimer.CallCallback()
at System.Threading.TimerQueueTimer.Fire()
at System.Threading.TimerQueue.FireNextTimers()
at System.Threading.TimerQueue.AppDomainTimerCallback()
Digging in a little, it seems that when HttpClient aborts the request before a relevant ServicePoint is created, HttpWebRequest attempts to create the ServicePoint, via ServicePointManager.FindServicePoint, which throws a RequestCanceled. Since this exception is thrown in the thread that attempts to cancel the request, it is not caught, and the process dies.
Am I missing something? Have you run into this issue?
HttpWebRequest.Abort() is throwing an exception on a background/timer thread. This has nothing to do with HttpClient's Task management.
The exception from HttpWebRequest.Abort() should be fixed in .NET 4.5 GDR1.
http://support.microsoft.com/kb/2750149
http://support.microsoft.com/kb/2750147
Looks like it's some kind of bug in how the async handler for HttpClient is managing the tasks. I was able to launch the items in parallel, but run them synchronously and it works. I'm not sure if you want to just prevent the unhandled error or not. This ran parallel tasks, but they aren't async really since I turned it off. On my computer I would always get to 5 rounds and it would crash. Even if i set it to timeout after a second, it's like the crashes in the threads would still blow up if they were async.
I think it's a bug, I can't imagine this is intended behavior.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
namespace TestCrash
{
class Program
{
static void Main(string[] args)
{
try
{
Parallel.ForEach(Enumerable.Range(1, 1000).ToList(), i =>
{
Console.WriteLine(i);
using (var c = new HttpClient { Timeout = TimeSpan.FromMilliseconds(1) })
{
var t = c.GetAsync("http://microsoft.com");
t.RunSynchronously(); //<--comment this line and it crashes
Console.WriteLine(t.Result);
}
});
}
catch (Exception x)
{
Console.WriteLine(x.Message);
}
Console.ReadKey();
}
}
}