예제 #1
0
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////

    public async void TaskContinueWithEventHandler()
    {
        AsyncTools.WhereAmI("1");         // main thread

        var originalTask = new Task(() => AsyncTools.WhereAmI("2"));

        var continuationTask1 = originalTask.ContinueWith(
            previousTask => AsyncTools.WhereAmI("3"),
            UnityScheduler.UpdateScheduler);             // main thread, Update context

        var continuationTask2 = continuationTask1.ContinueWith(
            previousTask => AsyncTools.WhereAmI("4"));             // background thread

        var continuationTask3 = continuationTask2.ContinueWith(
            previousTask => AsyncTools.WhereAmI("5"),
            UnityScheduler.FixedUpdateScheduler);             // main thread, FixedUpdate context

        var continuationTask4 = continuationTask3.ContinueWith(
            previousTask => AsyncTools.WhereAmI("6"));             // background thread

        originalTask.Start(UnityScheduler.ThreadPoolScheduler);    // start the task chain from a background thread

        await continuationTask4;

        Debug.Log("done");
    }
예제 #2
0
    private static async Task TestContextSwitch()
    {
        AsyncTools.WhereAmI("1");

        await AsyncTools.ToThreadPool();

        AsyncTools.WhereAmI("2");
        await 0;
        AsyncTools.WhereAmI("3");

        await AsyncTools.ToUpdate();

        AsyncTools.WhereAmI("4");
        await 0;
        AsyncTools.WhereAmI("5");

        await AsyncTools.ToLateUpdate();

        AsyncTools.WhereAmI("6");
        await 0;
        AsyncTools.WhereAmI("7");

        await AsyncTools.ToFixedUpdate();

        AsyncTools.WhereAmI("8");
        await 0;
        AsyncTools.WhereAmI("9");
    }
예제 #3
0
        public async Task GivenExampleAppRequiringArguments_WhenHaveArguments_ThenSucceeds()
        {
            var path = @"C:\Work\Github\Dotnetos\Module04-AsyncPart2\ExampleApp\bin\Debug\netcoreapp3.1\ExampleApp.exe";

            var result = await AsyncTools.RunProgramAsync(path, "argument");

            Assert.Equal("Hello argument!\r\nGoodbye.\r\n", result);
        }
        public async Task GivenExampleAppRequiringArguments_WhenHaveArguments_ThenSucceeds()
        {
            var path = @"..\..\..\..\..\ExampleApp\bin\x64\Debug\netcoreapp3.1\ExampleApp.exe";

            var result = await AsyncTools.RunProgramAsync(path, "argument");

            Assert.Equal("Hello argument!\r\nGoodbye.\r\n", result);
        }
예제 #5
0
        public async Task GivenExampleAppRequiringArguments_WhenHaveArguments_ThenSucceeds()
        {
            var path = @"../../../../ExampleApp/Release/ExampleApp";

            var result = await AsyncTools.RunProgramAsync(path, "argument");

            Assert.Equal("Hello argument!\nGoodbye.\n", result);
        }
예제 #6
0
        public async Task GivenExampleAppRequiringArguments_WhenHaveArguments_ThenSucceeds()
        {
            var location = Assembly.GetExecutingAssembly().Location;
            var path     = Path.Combine(location, @"..\..\..\..\..\ExampleApp\bin\Debug\netcoreapp3.1\ExampleApp.exe");
            var result   = await AsyncTools.RunProgramAsync(path, "argument");

            Assert.Equal("Hello argument!\r\nGoodbye.\r\n", result);
        }
예제 #7
0
        public long?Get(DynamicQuery query)
        {
            if (query == null)
            {
                throw new System.ArgumentNullException(nameof(query));
            }

            return(AsyncTools.RunSync(() => GetAsync(query)));
        }
예제 #8
0
        public long?Get(SqlQuerySpec query, FeedOptions feedOptions = null)
        {
            if (query == null)
            {
                throw new System.ArgumentNullException(nameof(query));
            }

            return(AsyncTools.RunSync(() => GetAsync(query, feedOptions)));
        }
예제 #9
0
        public async Task GivenExampleAppRequiringArguments_WhenNoArguments_ThenThrows()
        {
            var exception = await Record.ExceptionAsync(async() =>
                                                        await AsyncTools.RunProgramAsync(_path));

            Assert.NotNull(exception);
            Assert.IsType <Exception>(exception);
            Assert.StartsWith("Unhandled exception. System.Exception: Missing program argument.", exception.Message);
        }
예제 #10
0
        public long?Get(string sql, object parameters)
        {
            if (sql == null)
            {
                throw new System.ArgumentNullException(nameof(sql));
            }

            return(AsyncTools.RunSync(() => GetAsync(new DynamicQuery <AggregateResult>(sql, parameters).ToSqlQuerySpec())));
        }
예제 #11
0
        public async Task GivenExampleAppRequiringArguments_WhenNoArguments_ThenThrows()
        {
            var path      = @"C:\Work\Github\Dotnetos\Module04-AsyncPart2\ExampleApp\bin\Debug\netcoreapp3.1\ExampleApp.exe";
            var exception = await Record.ExceptionAsync(async() =>
                                                        await AsyncTools.RunProgramAsync(path));

            Assert.NotNull(exception);
            Assert.IsType <Exception>(exception);
            Assert.StartsWith("Unhandled exception. System.Exception: Missing program argument.", exception.Message);
        }
예제 #12
0
        public async Task GivenExampleAppRequiringArguments_WhenNoArguments_ThenThrows()
        {
            var location  = Assembly.GetExecutingAssembly().Location;
            var path      = Path.Combine(location, @"..\..\..\..\..\ExampleApp\bin\Debug\netcoreapp3.1\ExampleApp.exe");
            var exception = await Record.ExceptionAsync(async() =>
                                                        await AsyncTools.RunProgramAsync(path));

            Assert.NotNull(exception);
            Assert.IsType <Exception>(exception);
            Assert.StartsWith("Unhandled exception. System.Exception: Missing program argument.", exception.Message);
        }
예제 #13
0
    private async Task ShowRandomImages(int count, CancellationToken cancellationToken)
    {
        for (int i = 0; i < count; i++)
        {
            var image = await AsyncTools.DownloadAsBytesAsync("http://placeimg.com/320/200", cancellationToken);

            texture.LoadImage(image);
            rawImage.SetNativeSize();

            counterText.text = $"{i + 1} of {count}";

            if (i != count - 1)
            {
                await TaskEx.Delay(TimeSpan.FromSeconds(delayInSeconds), cancellationToken);
            }
        }
    }
    public async void ShowGoogleLogosAsync()     // can be on-click handler
    {
        button.interactable = false;

        var texture = new Texture2D(1, 1);

        rawImage.texture = texture;
        for (int i = 1; i <= 11; i++)
        {
            await .5f;
            var png = await AsyncTools.DownloadAsBytesAsync($"http://www.google.com/images/srpr/logo{i}w.png");

            texture.LoadImage(png);
            rawImage.SetNativeSize();
        }

        button.interactable = true;
    }
예제 #15
0
    private void RunTasksSynchronously()
    {
        /*
         * Fact #1: ThreadPoolScheduler supports running tasks on any thread.
         * Fact #2: MainThreadScheduler supports running tasks on the main thread only.
         *
         * If this method is called from the main thread, all the tasks will be executed on the main thread.
         *
         * If this method is called from a background thread, the tasks associated with the thread pool scheduler
         * will be executed on the current background thread, and the tasks associated with the main thread scheduler will be
         * executed on the main thread while the background thread will be blocked until the execution completes.
         */

        /*                   ATTENTION!!! ВНИМАНИЕ!!! ¡¡¡ATENCIÓN!!!
         *
         * Using UpdateScheduler, LateUpdateScheduler or FixedUpdateScheduler for running
         * tasks synchronously from the main thread will cause a DEADLOCK if the current
         * context doesn't match the task scheduler's type.
         *
         * E.g. don't call task.RunSynchronously(UnityScheduler.FixedUpdateScheduler) from
         * the Update method.
         *
         */

        AsyncTools.WhereAmI("1");

        var task = new Task(() => AsyncTools.WhereAmI("2"));

        task.RunSynchronously(UnityScheduler.UpdateScheduler);

        task = new Task(() => AsyncTools.WhereAmI("3"));
        task.RunSynchronously(UnityScheduler.ThreadPoolScheduler);

        task = new Task(() => AsyncTools.WhereAmI("4"));
        task.RunSynchronously(UnityScheduler.UpdateScheduler);

        task = new Task(() => AsyncTools.WhereAmI("5"));
        task.RunSynchronously();         // no scheduler => use default, which, in this case, is ThreadPoolScheduler

        task = new Task(() => AsyncTools.WhereAmI("6"));
        task.RunSynchronously(UnityScheduler.UpdateScheduler);
    }
    public override async void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        GUI.enabled = !isRunning;
        if (GUILayout.Button("Start"))
        {
            isRunning  = true;
            isCanceled = false;

            while (isCanceled == false)
            {
                await AsyncTools.ToThreadPool();

                AsyncTools.WhereAmI("1");

                await AsyncTools.ToEditorUpdate();

                AsyncTools.WhereAmI("2");

                await 1;
            }

            await AsyncTools.ToEditorUpdate();

            AsyncTools.WhereAmI("Stopped");

            isRunning = false;
            return;
        }

        GUI.enabled = isRunning;
        if (GUILayout.Button((isCanceled && isRunning) ? "Stopping" : "Stop"))
        {
            isCanceled = true;
        }
    }
예제 #17
0
    public async void AsyncAwaitEventHandler()
    {
        AsyncTools.WhereAmI("1");                                          // main thread, Update context

        var task1 = Task.Factory.StartNew(() => AsyncTools.WhereAmI("2")); // background thread

        var task2 = new Task(() => AsyncTools.WhereAmI("3"));              // main thread, FixedUpdate context

        task2.Start(UnityScheduler.FixedUpdateScheduler);

        var task3 = Task.Factory.StartNew(() => AsyncTools.WhereAmI("4"));         // background thread

        // returns execution of asynchronous method to the main thread,
        // if it was originally called from the main thread
        await TaskEx.WhenAll(task1, task2, task3);

        AsyncTools.WhereAmI("5");         // main thread, Update context

        await TaskEx.Delay(100).ConfigureAwait(false);

        AsyncTools.WhereAmI("6");         // can be any thread, since the previous line states that we don't care

        Debug.Log("done");
    }
예제 #18
0
        /// <summary>
        /// Replaces the document.
        /// </summary>
        /// <returns>The document.</returns>
        /// <param name="entity">Entity.</param>
        public T Replace(T entity)
        {
            var response = AsyncTools.RunSync(() => ReplaceAsync(entity));

            return(response);
        }
예제 #19
0
        /// <summary>
        /// Creates the document.
        /// </summary>
        /// <returns>The document.</returns>
        /// <param name="entity">Entity.</param>
        public T Create(T entity)
        {
            var response = AsyncTools.RunSync(() => CreateAsync(entity));

            return(response);
        }
예제 #20
0
 /// <summary>
 /// Gets the first or default document.
 /// </summary>
 /// <returns>The first document.</returns>
 /// <param name="query">Query.</param>
 public T GetFirstOrDefault(DynamicQuery query)
 {
     return(AsyncTools.RunSync(() => GetFirstOrDefaultAsync(query)));
 }
예제 #21
0
 /// <summary>
 /// Gets the first or default document.
 /// </summary>
 /// <returns>The first document.</returns>
 /// <param name="sql">Sql query.</param>
 /// <param name="parameters">Parameters.</param>
 public T GetFirstOrDefault(string sql, object parameters)
 {
     return(AsyncTools.RunSync(() => GetFirstOrDefaultAsync(new DynamicQuery <T>(sql, parameters).ToSqlQuerySpec())));
 }
예제 #22
0
 /// <summary>
 /// Gets the first or default document.
 /// </summary>
 /// <returns>The first document.</returns>
 /// <param name="query">Query.</param>
 public T GetFirstOrDefault(SqlQuerySpec query = null)
 {
     return(AsyncTools.RunSync(() => GetFirstOrDefaultAsync(query)));
 }
예제 #23
0
 /// <summary>
 /// Gets the list of documents.
 /// </summary>
 /// <returns>The documents.</returns>
 /// <param name="query">Query.</param>
 public IList <T> GetList(string query, object parameters = null)
 {
     return(AsyncTools.RunSync(() => GetListAsync(new DynamicQuery <T>(query, parameters).ToSqlQuerySpec())));
 }
예제 #24
0
 /// <summary>
 /// Gets the list of documents.
 /// </summary>
 /// <returns>The documents.</returns>
 /// <param name="query">Query.</param>
 public IList <T> GetList(DynamicQuery query)
 {
     return(AsyncTools.RunSync(() => GetListAsync(query)));
 }
예제 #25
0
 /// <summary>
 /// Gets the list of documents.
 /// </summary>
 /// <returns>The documents.</returns>
 /// <param name="query">Query.</param>
 public IList <T> GetList(SqlQuerySpec query)
 {
     return(AsyncTools.RunSync(() => GetListAsync(query)));
 }
예제 #26
0
파일: Mailer.cs 프로젝트: liyang-love/Drool
 /// <summary>
 /// Send email.
 /// </summary>
 public void Send(MailAddress from, MailAddressCollection tos, string subject, Dictionary <string, object> replacements = null, MailAddressCollection replyTos = null, MailAddressCollection ccs = null, IEnumerable <Attachment> attachments = null)
 {
     AsyncTools.RunSync(() => SendHelperAsync(from, tos, subject, replacements, replyTos, ccs, attachments));
 }
예제 #27
0
        /// <summary>
        /// Delete the specified id.
        /// </summary>
        /// <returns><c>true</c> if document has been deleted; otherwise, <c>false</c>.</returns>
        /// <param name="id">The id of the document.</param>
        public bool Delete(string id)
        {
            var response = AsyncTools.RunSync(() => DeleteAsync(id));

            return(response);
        }
예제 #28
0
        /// <summary>
        /// Gets all documents.
        /// </summary>
        /// <returns>The documents.</returns>
        public IList <T> GetAll()
        {
            var response = AsyncTools.RunSync(GetAllAsync);

            return(response);
        }
예제 #29
0
파일: Mailer.cs 프로젝트: liyang-love/Drool
 /// <summary>
 /// Send email.
 /// </summary>
 public void Send(string from, string to, string subject, Dictionary <string, object> replacements = null)
 {
     AsyncTools.RunSync(() => SendHelperAsync(new MailAddress(from), new MailAddressCollection {
         new MailAddress(to)
     }, subject, replacements));
 }
예제 #30
0
        /// <summary>
        /// Delete the specified id.
        /// </summary>
        /// <returns><c>true</c> if document has been deleted; otherwise, <c>false</c>.</returns>
        /// <param name="entity">Entity.</param>
        public bool Delete(T entity)
        {
            var response = AsyncTools.RunSync(() => DeleteAsync(BaseRepository <T> .GetId(entity)));

            return(response);
        }