Asynchronous API Calls Task Async Await

Greg Kolinski edited this page Sep 20, 2017 · 1 revision

Back To API Calls Home


Asynchronous Task/Async/Await Usage

ECGridOS uses the Event-based Asynchronous Pattern (EAP) for most of its API Methods. An overview of this pattern from MSDN can be found here. To use async and await with these types of events you need to wrap them in a Task. One way this can be done is by using TransferCompletion and TaskCompletionSource. Please see this MSDN Blog Post for more information on Tasks and the Event-based Asynchronous Pattern.

Code Examples

C# Console

using System;
using System.Threading.Tasks;
using System.Web.Services.Protocols;
using System.Xml;
using ECGridService = ECGrid_API.net.ecgridos;

namespace ECGrid_API
{
    public class ECGrid_Main
    {
        /// <summary>
        /// Main Method for Running the Program
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            try
            {
                using (ECGridService.ECGridOSAPIv3 ECGrid = new ECGridService.ECGridOSAPIv3())
                {
                    try
                    {
                        string SessionID = "00000000-0000-0000-0000-000000000000";

                        Console.WriteLine("Pre Async Call");
                        ECGridAsync AsyncCalls = new ECGridAsync();
                        Task<string> FullName = AsyncCalls.GetFullName(ECGrid, SessionID);
                        Console.WriteLine("Post Async Call");

                        Console.WriteLine("Who Am I?");

                        Console.WriteLine($"{FullName.Result}");

                    }
                    catch (SoapException SoapEx)
                    {
                        // See SOAP Exceptions in the Appendix
                        var ECG_Ex = CatchException(SoapEx);
                        Console.WriteLine($"ECGridOS Soap Exception: {ECG_Ex.ErrorCode} , Item: {ECG_Ex.ErrorItem}, Message: {ECG_Ex.ErrorMessage}, String: {ECG_Ex.ErrorString}");
                    }
                } // END USING
            }
            catch (Exception ex){ Console.WriteLine("Unhandled Exception: " + ex.ToString()); }

            Console.WriteLine("Press any Key to quit...");
            Console.ReadKey();
        } // END MAIN
    } // END CLASS

    public class ECGridAsync
    {
        public async Task<string> GetFullName(ECGridService.ECGridOSAPIv3 ECGrid, string SessionID)
        {
            var taskResults = await ECGrid.WhoAmIAsyncTask(SessionID);
            var User = taskResults.Result;
            return $"{User.FirstName} {User.LastName}";
        }
    }

    internal static class Extension
    {
        private static void TransferCompletion<T>(TaskCompletionSource<T> tcs, System.ComponentModel.AsyncCompletedEventArgs e, Func<T> getResult)
        {
            if (e.Error != null)
            {
                tcs.TrySetException(e.Error);
            }
            else if (e.Cancelled)
            {
                tcs.TrySetCanceled();
            }
            else
            {
                tcs.TrySetResult(getResult());
            }
        }

        public static Task<ECGridService.WhoAmICompletedEventArgs> WhoAmIAsyncTask(this ECGridService.ECGridOSAPIv3 ECGrid, string SessionID)
        {
            var tcs = new TaskCompletionSource<ECGridService.WhoAmICompletedEventArgs>();
            ECGrid.WhoAmICompleted += (s, e) => TransferCompletion(tcs, e, () => e);
            ECGrid.WhoAmIAsync(SessionID);
            return tcs.Task;
        }
    }

} // END NAMESPACE

C# Windows Forms

Form1

using System;
using System.Threading.Tasks;
using System.Windows.Forms;
using ECGridService = ECGridOS_Async.net.ecgridos;

namespace ECGridOS_Async
{
    public partial class Form1 : Form
    {
        ECGridService.ECGridOSAPIv3 ECGrid = new ECGridService.ECGridOSAPIv3();

        public Form1()
        {
            InitializeComponent();
        }

        private async void WhoAmI_Button_Click(object sender, EventArgs e)
        {
            string SessionID = "00000000-0000-0000-0000-000000000000";
            var taskResults = await ECGrid.WhoAmIAsyncTask(SessionID);
            var User = taskResults.Result;

            WhoAmITextBox.Text = $"{User.FirstName} {User.LastName}";
        }
    }

    internal static class Extension
    {
        private static void TransferCompletion<T>(TaskCompletionSource<T> tcs, System.ComponentModel.AsyncCompletedEventArgs e, Func<T> getResult)
        {
            if (e.Error != null)
            {
                tcs.TrySetException(e.Error);
            }
            else if (e.Cancelled)
            {
                tcs.TrySetCanceled();
            }
            else
            {
                tcs.TrySetResult(getResult());
            }
        }

        public static Task<ECGridService.WhoAmICompletedEventArgs> WhoAmIAsyncTask(this ECGridService.ECGridOSAPIv3 ECGrid, string SessionID)
        {
            var tcs = new TaskCompletionSource<ECGridService.WhoAmICompletedEventArgs>();
            ECGrid.WhoAmICompleted += (s, e) => TransferCompletion(tcs, e, () => e);
            ECGrid.WhoAmIAsync(SessionID);
            return tcs.Task;
        }
    }
}

Back To API Calls Home

Clone this wiki locally
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.