Si consideri il seguente frammento di codice:Come creare un metodo asincrono in C# 4 secondo le migliori pratiche?
public static Task<string> FetchAsync()
{
string url = "http://www.example.com", message = "Hello World!";
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = WebRequestMethods.Http.Post;
return Task.Factory.FromAsync<Stream>(request.BeginGetRequestStream, request.EndGetRequestStream, null)
.ContinueWith(t =>
{
var stream = t.Result;
var data = Encoding.ASCII.GetBytes(message);
Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite, data, 0, data.Length, null, TaskCreationOptions.AttachedToParent)
.ContinueWith(t2 => { stream.Close(); });
})
.ContinueWith<string>(t =>
{
var t1 =
Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null)
.ContinueWith<string>(t2 =>
{
var response = (HttpWebResponse)t2.Result;
var stream = response.GetResponseStream();
var buffer = new byte[response.ContentLength > 0 ? response.ContentLength : 0x100000];
var t3 = Task<int>.Factory.FromAsync(stream.BeginRead, stream.EndRead, buffer, 0, buffer.Length, null, TaskCreationOptions.AttachedToParent)
.ContinueWith<string>(t4 =>
{
stream.Close();
response.Close();
if (t4.Result < buffer.Length)
{
Array.Resize(ref buffer, t4.Result);
}
return Encoding.ASCII.GetString(buffer);
});
t3.Wait();
return t3.Result;
});
t1.Wait();
return t1.Result;
});
}
deve restituire Task<string>
, inviare richiesta HTTP POST con alcuni dati, restituisce un risultato dal web server in una forma di stringa ed essere il più efficiente possibile.
- Hai riscontrato problemi relativi al flusso asincrono nell'esempio sopra?
- è ok per avere .Wait() all'interno .ContinueWith() in questo esempio
- Hai visto altri problemi con questa pace di codice (tenendo da parte la gestione delle eccezioni per ora)?
È necessario accettare alcune risposte dalle altre domande – Jimmy
È possibile prendere in considerazione la possibilità di rinominare l'oggetto Task poiché esiste già un oggetto Task in .NET 4. Mentre è possibile farli funzionare insieme, potrebbe essere più semplice cambiare semplicemente il proprio nomenclatura. –
Mystere Man, non ho nessuna dichiarazione di attività personalizzata. Il tipo di attività che sto usando proviene da .NET 4.0 BCL. –