我有一個Windows通用項目與多個API調用。 一種方法拒絕工作eventhought我的其他調用工作完全是這樣的。 我試過using
關鍵字認爲它可以解決問題。HttpClient上ObjectDisposedException
功能:
public async Task<User> GetNewUser(string user_guid, OAuthTokens OAuth)
{
String userguidJSON = VALIDJSON_BELIEVE_ME;
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", Encrypt(OAuth.Accesstoken));
using (HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, BASE_URL + URL_USERS + "/data"))
{
req.Content = new StringContent(userguidJSON, Encoding.UTF8, "application/json");
await httpClient.SendAsync(req).ContinueWith(respTask =>
{
Debug.WriteLine(req.Content.ReadAsStringAsync()); //Error is thrown ono this line
});
return null;
}
}
}
編輯
public async Task<User> GetNewUser(string user_guid, OAuthTokens OAuth)
{
String userguidJSON = VALIDJSON_BELIEVE_ME;
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", Encrypt(OAuth.Accesstoken));
using (HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, BASE_URL + URL_USERS + "/data"))
{
req.Content = new StringContent(userguidJSON, Encoding.UTF8, "application/json");
await httpClient.SendAsync(req);
var result = await req.Content.ReadAsStringAsync(); //Cannot access a disposed object. Object name: 'System.Net.Http.StringContent'.
Debug.WriteLine(result);
return null;
}
}
}
堆棧跟蹤
at System.Net.Http.HttpContent.CheckDisposed()
at System.Net.Http.HttpContent.ReadAsStringAsync()
at Roadsmart.Service.RoadsmartService.<GetNewUser>d__2e.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Roadsmart.ViewModel.SettingsPageViewModel.<SetNewProfilePicture>d__1e.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>b__3(Object state)
at System.Threading.WinRTSynchronizationContext.Invoker.InvokeCore()
你爲什麼要用'ContinueWith'混合'await'? – 2015-03-31 13:36:09
你爲什麼使用'ContinueWith'?處理異步/等待時,不需要使用'ContinueWith'。 – 2015-03-31 13:36:32