Questo è l'errore che ottengo:uno o più errori si sono verificati: PostAsJsonAsync
One or more errors occurred.
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 myProject.mymethod(Int32[] myIds) in path\MyClass.cs:line 758
Ed ecco che il metodo:
private void mymethod(int[] myIds)
{
var uri = new Uri(string.Format(UriPath, string.Format(MyPath)));
var client = GetHttpClient(uri);
var postModel = new PostModel
{
Ids = myIds,
LastUpdate = NewItem ? null : _lastUpdated
};
if (client != null)
{
var response = client.PostAsJsonAsync(uri, postModel).Result;//this line crashes
if (response.IsSuccessStatusCode)
{
//doSomething
}
}
}
io chiamo un sacco di metodi come questo e tutti loro lavorare ad eccezione questo. Quando viene colpito, ci vuole un sacco di tempo e quindi questa eccezione è tiri. Con tutti gli altri metodi l'errore non si verifica.
Questa è l'eccezione interna:
Inner.System.Threading.Tasks.TaskCanceledException: A task was canceled.
Ecco il mio metodo getClient():
private HttpClient GetHttpClient(Uri uri)
{
var handler = new HttpClientHandler
{
CookieContainer = CoockieContainer
};
return new HttpClient(handler)
{
BaseAddress = uri
};
}
Ecco il metodo API:
[HttpPost]
public IList<MyModel> MyAPIMethod(PostModel model)
{
List<MyModel> myTranslations;
using (var db = new myEntities(GetDbConnStrByUser(new GetCookies().GetUserName())))
{
myTranslations = db.tblTranslations.Where(it => model.Ids.Contains(it.id)
&& (!model.Update.HasValue || it.update > model.LastUpdate.Value))
.Select(it => new MyModel
{
Id = it.id,
Name = it.name,
Description = it.desc,
LanguageId = it.language_id
}).ToList();
}
return myTranslations.GroupBy(x => new { x.Id, x.LanguageId }).Select(x => x.First()).ToList();
}
Forse si verifica un timeout.
Fiddler restituisce questo errore: l'operazione di attesa è scaduta.
non utilizzare il blocco dichiarazioni, andare con asincrono, invece. Guarda l'eccezione interiore. –
@JeroenVannevel Cosa intendi con dichiarazioni bloccanti? –
La chiamata a ".Result" è un'istruzione sincrona; non usi mai l'asincronicità che potresti avere. Più qui sul corretto utilizzo async-await: http://msdn.microsoft.com/en-us/library/hh191443.aspx –