/// <summary> /// Creates an <see cref="Task{TResult}"/> wrapper for the Unity <see cref="AssetBundleRequest"/>. /// </summary> /// <param name="op">The source operation.</param> public static Task <T> ToTask <T>(this AssetBundleRequest op) where T : UnityEngine.Object { var result = new TaskCompletionSource <T>(op); AsyncUtility.AddCompletionCallback(op, () => result.TrySetResult(op.asset as T)); return(result.Task); }
/// <summary> /// Plays an animator state. /// </summary> /// <param name="anim">Target animator instance.</param> /// <param name="stateNameHash">Hash of the state name.</param> /// <param name="layer">The layer index. If layer is -1, it plays the first state with the given state name.</param> /// <returns>An asynchronous operation that can be used to track the animation progress.</returns> public static IAsyncOperation PlayAsync(this Animator anim, int stateNameHash, int layer = -1) { var result = new Helpers.PlayAnimatorResult(anim, stateNameHash, layer, AsyncUtility.GetUpdateSource()); result.Start(); return(result); }
public static Task ToTask(this UnityWebRequest request) { var result = new TaskCompletionSource <object>(request); AsyncUtility.AddCompletionCallback(request, () => OnTaskCompleted(result, request)); return(result.Task); }
public static Task <T> ToTask <T>(this UnityWebRequest request) where T : class { var result = new TaskCompletionSource <T>(request); AsyncUtility.AddCompletionCallback(request, () => OnTaskCompleted(result, request)); return(result.Task); }
private async static void MyAsyncExample() { AsyncUtility myUtility = new AsyncUtility(); string myWord = await myUtility.BottlesOfBeerSongAsync(); Console.WriteLine(myWord); }
/// <inheritdoc/> protected override void OnStarted() { if (_www.isDone) { SetCompleted(); } else { AsyncUtility.AddCompletionCallback(_www, SetCompleted); } }
public static void RunWeek7Classwork() { MyLinqEample(); MyAsyncExample(); SimpleTaskExample(); void MyLinqEample() { string[] names = { "Tom", "Don", "Harry", "Mary", "Jay" }; string[] bnames = { "Tom", "Dick", "Sarah" }; IEnumerable <string> query = names; IEnumerable <string> query2 = bnames .Where(n => n.Contains("a")) .OrderBy(n => n.Length) .Select(n => n.ToUpper()); foreach (string name in query) { Console.WriteLine(name); } } async void MyAsyncExample() { AsyncUtility myUtility = new AsyncUtility(); string MyWord = await myUtility.BottlesOfBeerAsync(); Console.WriteLine(MyWord); } void SimpleTaskExample() { Thread.CurrentThread.Name = "Main"; //Create a task and a supply a user delegate by using a lambda expression Task task = new Task(() => Console.WriteLine("Hello from task!")); //Define a run with task //Task task = Task.Run(() => Console.WriteLine("Hello from task!")); //Start the task task.Start(); //Output a message from the calling task Console.WriteLine("Hello from thread {0}.", Thread.CurrentThread.Name); task.Wait(); } }
/// <summary> /// Creates an <see cref="Task"/> wrapper for the Unity <see cref="AsyncOperation"/>. /// </summary> /// <param name="op">The source operation.</param> public static Task ToTask(this AsyncOperation op) { if (op.isDone) { return(Task.CompletedTask); } else { var result = new TaskCompletionSource <object>(op); AsyncUtility.AddCompletionCallback(op, () => result.TrySetResult(null)); return(result.Task); } }
void ITransport.SendRequestAsync(ServiceRequest request) { if (request == null) { throw new ArgumentNullException("request"); } Uri requestUri = new Uri(uri.Replace(TOKEN_ACTION, request.Action).Replace(TOKEN_SERVICE, request.Service)); HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(requestUri); httpRequest.Method = "POST"; httpRequest.Accept = httpRequest.ContentType = RpcUtils.HTTP_RPC_MIME_TYPE; #if !SILVERLIGHT && !CF2 httpRequest.AutomaticDecompression = DecompressionMethods.None; #endif #if !SILVERLIGHT httpRequest.UserAgent = "protobuf-net"; httpRequest.Headers.Add(RpcUtils.HTTP_RPC_VERSION_HEADER, "0.1"); #endif Action <Exception> handler = delegate(Exception ex) { request.OnException(ex); }; Action <WebResponse> onResponse = delegate(WebResponse webResponse) { try { using (Stream stream = webResponse.GetResponseStream()) { object result = RpcUtils.UnpackArgs(stream, request.Method, request.Args, RpcUtils.IsResponseArgument); request.OnResponse(result); } } catch (Exception ex) { handler(ex); } }; Action <Stream> onGetRequest = delegate(Stream stream) { try { RpcUtils.PackArgs(stream, request.Method, null, request.Args, RpcUtils.IsRequestArgument); stream.Close(); AsyncUtility.RunAsync(httpRequest.BeginGetResponse, httpRequest.EndGetResponse, onResponse, handler); } catch (Exception ex) { //Trace.WriteLine(ex, GetType() + ":" + request.Method.DeclaringType.Name); handler(ex); } }; AsyncUtility.RunAsync(httpRequest.BeginGetRequestStream, httpRequest.EndGetRequestStream, onGetRequest, handler); }
/// <inheritdoc/> protected override void OnStarted() { if (_request.isDone) { SetCompleted(); } else if (_request.isModifiable) { #if UNITY_2017_2_OR_NEWER _op = _request.SendWebRequest(); #else _op = _request.Send(); #endif AsyncUtility.AddCompletionCallback(_op, SetCompleted); } }
/// <inheritdoc/> protected override void OnStarted() { Debug.Assert(_op != null); if (_op.isDone) { OnSetCompleted(_op); } else { #if UNITY_2017_2_OR_NEWER // Starting with Unity 2017.2 there is AsyncOperation.completed event _op.completed += OnSetCompleted; #else AsyncUtility.AddCompletionCallback(_op, () => OnSetCompleted(_op)); #endif } }
private async static void MyAsyncExample() { //bottles of beer song /* * AsyncUtility myUtility = new AsyncUtility(); * string myWord = await myUtility.BottlesOfBeerSongAsync(); * Console.WriteLine(myWord); */ // API call within AsyncUtility // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/ // AsyncUtility myAPI = new AsyncUtility(); int myNum = await myAPI.AccessTheWebAsync(); Console.WriteLine(myNum); }
/// <summary> /// Loads a <see cref="Scene"/> from an asset bundle. /// </summary> /// <param name="assetBundle">The source asset bundle.</param> /// <param name="loadMode">The scene load mode.</param> /// <param name="sceneName">Name of the scene to load or <see langword="null"/> to load the any scene.</param> public static IAsyncOperation <Scene> LoadSceneAsync(this AssetBundle assetBundle, LoadSceneMode loadMode, string sceneName) { if (!assetBundle.isStreamedSceneAssetBundle) { throw new InvalidOperationException(); } if (string.IsNullOrEmpty(sceneName)) { var scenePaths = assetBundle.GetAllScenePaths(); if (scenePaths != null && scenePaths.Length > 0 && !string.IsNullOrEmpty(scenePaths[0])) { sceneName = Path.GetFileNameWithoutExtension(scenePaths[0]); } if (string.IsNullOrEmpty(sceneName)) { throw new AssetLoadException("The asset bundle contains no scenes.", null, typeof(Scene)); } } return(AsyncUtility.LoadSceneAsync(sceneName, loadMode)); }
/// <summary> /// Invokes the test method on the given test class instance. This method sets up support for "async void" /// test methods, ensures that the test method has the correct number of arguments, then calls <see cref="CallTestMethod"/> /// to do the actual method invocation. It ensure that any async test method is fully completed before returning, and /// returns the measured clock time that the invocation took. This method should NEVER throw; any exceptions should be /// placed into the aggregator in <paramref name="ctxt"/>. /// </summary> /// <param name="ctxt">The context that describes the current test</param> /// <param name="testClassInstance">The test class instance</param> /// <returns>Returns the amount of time the test took to run, in seconds</returns> protected virtual async ValueTask <decimal> InvokeTestMethodAsync( TContext ctxt, object?testClassInstance) { var oldSyncContext = default(SynchronizationContext); var asyncSyncContext = default(AsyncTestSyncContext); try { if (AsyncUtility.IsAsyncVoid(ctxt.TestMethod)) { oldSyncContext = SynchronizationContext.Current; asyncSyncContext = new AsyncTestSyncContext(oldSyncContext); SetSynchronizationContext(asyncSyncContext); } var elapsed = await ExecutionTimer.MeasureAsync( () => ctxt.Aggregator.RunAsync( async() => { var parameterCount = ctxt.TestMethod.GetParameters().Length; var valueCount = ctxt.TestMethodArguments == null ? 0 : ctxt.TestMethodArguments.Length; if (parameterCount != valueCount) { ctxt.Aggregator.Add( new InvalidOperationException( $"The test method expected {parameterCount} parameter value{(parameterCount == 1 ? "" : "s")}, but {valueCount} parameter value{(valueCount == 1 ? "" : "s")} {(valueCount == 1 ? "was" : "were")} provided." ) ); } else { var result = CallTestMethod(ctxt, testClassInstance); var valueTask = AsyncUtility.TryConvertToValueTask(result); if (valueTask.HasValue) { await valueTask.Value; } else if (asyncSyncContext != null) { var ex = await asyncSyncContext.WaitForCompletionAsync(); if (ex != null) { ctxt.Aggregator.Add(ex); } } } } ) ); return((decimal)elapsed.TotalSeconds); } finally { if (asyncSyncContext != null) { SetSynchronizationContext(oldSyncContext); } } }
private void ListenForContext() { AsyncUtility.RunAsync( listener.BeginGetContext, listener.EndGetContext, gotContext, null); }
/// <inheritdoc/> public void OnCompleted(Action continuation) { _callback = continuation; AsyncUtility.StartCoroutine(this); }
/// <inheritdoc/> public void OnCompleted(Action continuation) { AsyncUtility.AddCompletionCallback(_op, continuation); }