I hope someone has an explanation to this, because it drives me nuts.
I have the following code in a WinForms application to upload a file using HttpClient to a Web API service.
ProgressMessageHandler progressMsgHandler = new ProgressMessageHandler();
progressMsgHandler.HttpSendProgress += (s, e) =>
{
this.InvokeIfNeeded(() =>
{
// LOG
this.AddLogLine("Progress: " + e.ProgressPercentage.ToString());
});
};
using (var client = HttpClientFactory.Create(progressMsgHandler))
{
using (var content = new MultipartFormDataContent())
{
var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
var streamContent = new StreamContent(stream);
content.Add(streamContent);
var url = String.Format("{0}?src={1}", STR_URL_FILEMGMT, "IM");
client.PostAsync(new Uri(url), content).ContinueWith(task =>
{
if (task.Result.IsSuccessStatusCode)
{
this.InvokeIfNeeded(() =>
{
// LOG
this.AddLogLine("File has been uploaded OK!");
});
}
else
this.InvokeIfNeeded(() =>
{
// LOG
this.AddLogLine(String.Format("Error during upload: '{0}'", task.Exception.Message));
});
});
}
}
Please note, entire code listed is also wrapped into a try catch where exception would be printed, if any.
Very weird to me is that I don't get any log line printed at all. Neither for progress, neither for posting with success, neither for posting with errors nor in the global try catch.
During debug, I see the code executing, but doesn't hit any breakpoints where the log lines are.
Probably I don't use correctly HttpClient or these tasks (I am beginner at this btw)? Does anyone know what's going wrong with my code?
UPDATE (after getting the solution from Noseratio):
Extra information which helps me understand that HttpClient does not need to be disposed can be found here
In your code, client.PostAsync
returns instantly (while the operation continues in the background). This unwinds both of your using
statements, so the HttpClient
object gets disposed of before the upload has finished.
If you want to utilize using
here, you'd need to use await
instead of ContinueWith
:
var result = await client.PostAsync(...);
if (result.IsSuccessStatusCode)
{
// ...
}
If you need to target .NET 4.0 but develop with VS2012+ , you still can use async/await
, Microsoft provides the Microsoft.Bcl.Async
library for that.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.