async-await

Can you explain why the exception is not caught if I do not await an async task?

巧了我就是萌 提交于 2019-12-22 11:03:11
问题 Starting from an issue I had on my code, I've created this simple app to recreate the problem: private async void button1_Click(object sender, EventArgs e) { Task task = Task.Run(() => { TestWork(); }); try { await task; MessageBox.Show("Exception uncaught!"); } catch (Exception) { MessageBox.Show("Exception caught!"); } } private async void button2_Click(object sender, EventArgs e) { Task task = TestWork(); try { await task; MessageBox.Show("Exception uncaught!"); } catch (Exception) {

Async Methods Confusion [duplicate]

亡梦爱人 提交于 2019-12-22 11:02:50
问题 This question already has answers here : async/await function comparison (3 answers) Closed 3 years ago . I'm trying to wrap my head around asynchronous methods and I am wondering what the difference is between the following two methods. public Task Add(Tenant tenant) { DbContext.Tenants.Add(tenant); return DbContext.SaveChangesAsync(); } public async Task Add(Tenant tenant) { DbContext.Tenants.Add(tenant); await DbContext.SaveChangesAsync(); } 回答1: First one is synchronous method, which

Application.DoEvents vs await Task.Delay in a loop

為{幸葍}努か 提交于 2019-12-22 10:56:40
问题 Much to my discontent, I need to use a WebBrowser control in one of my apps. One of the things I also need to do is wait for an element to become visible/class changes/etc, which happens well after the DocumentCompleted event is fired, making the event close to useless in my case. So currently I have something like... while (webBrowser.Document?.GetElementById("id")?.GetAttribute("classname") != "class") { Application.DoEvents(); Thread.Sleep(1); } Now I've read in multiple places that

How to include task parameter In array of tasks exception handling

淺唱寂寞╮ 提交于 2019-12-22 10:49:24
问题 The thread Nesting await in Parallel.ForEach has an answer suggested to use Task.WhenAll to run multiple (MaxDegreeOfParallelism) asynchronous tasks in parallel, not waiting until previous task is completed. public static Task ForEachAsync<T>( this IEnumerable<T> source, int dop, Func<T, Task> body) { return Task.WhenAll( from partition in Partitioner.Create(source).GetPartitions(dop) select Task.Run(async delegate { using (partition) while (partition.MoveNext()) await body(partition.Current)

System.Net.Http missing?

放肆的年华 提交于 2019-12-22 10:37:15
问题 I am trying to run Test.aspx: <%@ Page language="c#" EnableViewState="true" ContentType="text/html" Async="true" %> <script language="C#" runat="server"> void Page_Load(Object Src, EventArgs E ) { RegisterAsyncTask(new PageAsyncTask(BindData)); } private async System.Threading.Tasks.Task BindData() { Response.Write("Hello?<br /><br />"); using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient()) { Response.Write(await httpClient.GetStringAsync("http://www.google.com"));

Why async await doesn't working on IIS, but it's working on IIS Express

社会主义新天地 提交于 2019-12-22 10:34:27
问题 I don't understand, why async/await doesn't resolve problem with IIS threads. I see that we have limit on IIS threads equals 10, when I use IIS and no limits for IIS express. I add 2 methods in HomeController for repeat this problem. One of them (method) use Thread.Sleep and other use async/await. Of course I use logger (NLog) for describe this problem in more details. I use apache-jmeter-3.0 with 100 parallel request for one url as stress test. I was very surprised when the test execution

Catch an async lambda exception

ε祈祈猫儿з 提交于 2019-12-22 10:22:40
问题 I am working on Windows 8 (using C#) and when using the async keyword there's a scenario where i can't seem to handle exceptions well. The scenario involves launching an async lambda, posting it to run on the UI thread. Exceptions that occur during the execution of the lambda code gets re-thrown on the calling thread, with no ability to catch them properly. Example: this block of code is executed on some worker thread, and tries to schedule work on the UI thread: await Window.Current

Convert synchronous zip operation to async

天大地大妈咪最大 提交于 2019-12-22 10:17:38
问题 We got an existing library where some of the methods needs to be converted to async methods. However I'm not sure how to do it with the following method (errorhandling has been removed). The purpose of the method is to zip a file and save it to disk. (Note that the zip class doesn't expose any async methods.) public static bool ZipAndSaveFile(string fileToPack, string archiveName, string outputDirectory) { var archiveNameAndPath = Path.Combine(outputDirectory, archiveName); using (var zip =

Python 3.5 aiohttp blocks even when using async/await

穿精又带淫゛_ 提交于 2019-12-22 10:07:51
问题 I'm running a test aiohttp webserver: #!/usr/bin/env python3 from aiohttp import web import time import asyncio import random import string import logging logger = logging.getLogger('webserver') logger.setLevel(logging.INFO) handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) def randomword(length): return ''.join(random.choice(string.ascii_lowercase) for i in range

What if not await the task?

蓝咒 提交于 2019-12-22 10:03:31
问题 Here is my code: private static Stopwatch _stopwatch; static void PrintException(Exception ex) { Console.WriteLine(_stopwatch.Elapsed); Console.WriteLine(ex); } static void ThrowException1() { throw new InvalidAsynchronousStateException(); } static void ThrowException2() { throw new NullReferenceException(); } static async Task ExecuteTask1() { await Task.Delay(1000); ThrowException1(); } static async Task ExecuteTask2() { await Task.Delay(2000); ThrowException2(); } static async Task Execute