You can use TaskFactory.FromAsync to convert APM to TAP , creating many tiny extension methods, such as:
public static Task<Stream> GetRequestStreamAsync(this WebRequest request) { return TaskFactory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, null); }
and do the same for WebRequest.GetResponse and (if necessary) Stream.Write , Stream.Flush , etc.
Then you can write your actual logic using async and await without callbacks:
public async Task DefLoginAsync() { postData = "My Data To Post"; var url = new Uri("Url To Post to", UriKind.Absolute); webRequest = WebRequest.Create(url); webRequest.Method = "POST"; webRequest.ContentType = "text/xml"; using (Stream postStream = await webRequest.GetRequestStreamAsync()) { byte[] byteArray = Encoding.UTF8.GetBytes(postData); await postStream.WriteAsync(byteArray, 0, byteArray.Length); await postStream.FlushAsync(); } try { string Response; using (var response = (HttpWebResponse)await webRequest.GetResponseAsync()); using (Stream streamResponse = response.GetResponseStream()) using (StreamReader streamReader = new StreamReader(streamResponse)) { Response = await streamReader.ReadToEndAsync(); } if (Response == "") {
source share