async-await

Why coroutines cannot be used with run_in_executor?

▼魔方 西西 提交于 2020-01-22 12:20:26
问题 I want to run a service that requests urls using coroutines and multithread. However I cannot pass coroutines to the workers in the executor. See the code below for a minimal example of this issue: import time import asyncio import concurrent.futures EXECUTOR = concurrent.futures.ThreadPoolExecutor(max_workers=5) async def async_request(loop): await asyncio.sleep(3) def sync_request(_): time.sleep(3) async def main(loop): futures = [loop.run_in_executor(EXECUTOR, async_request,loop) for x in

Is there any way to create a async stream generator that yields the result of repeatedly calling a function?

懵懂的女人 提交于 2020-01-22 02:21:25
问题 I want to build a program that collects weather updates and represents them as a stream. I want to call get_weather() in an infinite loop, with 60 seconds delay between finish and start . A simplified version would look like this: async fn get_weather() -> Weather { /* ... */ } fn get_weather_stream() -> impl futures::Stream<Item = Weather> { loop { tokio::timer::delay_for(std::time::Duration::from_secs(60)).await; let weather = get_weather().await; yield weather; // This is not supported //

C# async / await unobserved exception

自作多情 提交于 2020-01-21 12:47:22
问题 I'm trying to understand why the following code: async void Handle_Clicked(object sender, System.EventArgs e) { try { await CrashAsync("aaa"); } catch (Exception exception) { Log($"observed exception"); Log($"Exception: {exception.Message}"); } } private async Task CrashAsync(string title) { Log($"CrashAsync ({title}) - before"); await Task.Delay(1000); throw new Exception($"CrashAsync ({title})"); Log($"CrashAsync ({title}) - after"); } produces the expected result: thread #1: CrashAsync

Call Async Method in Page_Load

◇◆丶佛笑我妖孽 提交于 2020-01-21 12:41:17
问题 static async void SendTweetWithSinglePicture(string message, string image) { var auth = new SingleUserAuthorizer { CredentialStore = new SingleUserInMemoryCredentialStore { ConsumerKey = "", ConsumerSecret = "", AccessToken = "", AccessTokenSecret = "" } }; var context = new TwitterContext(auth); var uploadedMedia = await context.UploadMediaAsync(File.ReadAllBytes(@image)); var mediaIds = new List<ulong> { uploadedMedia.MediaID }; await context.TweetAsync( message, mediaIds ); } protected

Why does this async/await code NOT cause a deadlock?

拈花ヽ惹草 提交于 2020-01-21 12:13:31
问题 I have found the following example in Jon Skeet's "C# in depth. 3rd edition": static async Task<int> GetPageLengthAsync(string url) { using (HttpClient client = new HttpClient()) { Task<string> fetchTextTask = client.GetStringAsync(url); int length = (await fetchTextTask).Length; return length; } } public static void Main() { Task<int> lengthTask = GetPageLengthAsync("http://csharpindepth.com"); Console.WriteLine(lengthTask.Result); } I expected that this code would deadlock, but it does not.

How can I run an async function using the schedule library?

大憨熊 提交于 2020-01-21 09:10:15
问题 I'm writing a discord bot using discord.py rewrite, and I want to run a function every day at a certain time. I'm not experienced with async functions at all and I can't figure out how to run one without using "await." This is only a piece of my code which is why some things may not be defined. async def send_channel(): try: await active_channel.send('daily text here') except Exception: active_channel_id = None active_channel = None async def timer(): while True: schedule.run_pending() await

Angular data binding won't work with async/await, yet it will with promises

最后都变了- 提交于 2020-01-21 07:22:46
问题 Data bindings don't get updated if their values are changed after an await statement. handle() { this.message = 'Works' } async handle() { this.message = 'Works' } async handle() { await new Promise((resolve, reject) => { resolve() }) this.message = 'Works' } async handle() { await new Promise((resolve, reject) => { setTimeout(() => resolve(), 3000) }) this.message = 'Doesn\'t work' } handle() { new Promise((resolve, reject) => { setTimeout(() => resolve(), 3000) }) .then(() => this.message =

Handle cancellation of async method

不问归期 提交于 2020-01-21 05:33:05
问题 I'm using Parse as a data store for an app, and I am implementing their Facebook Login functionality. AFAIK, this Login method isn't any different than other async methods so hopefully it applies. So there is a Login.xaml page, that has a button for "Login with Facebook", and tapping this button takes you to the FacebookLogin.xaml page which contains only the WebBrowser control as per the linked Parse documenation. In ContentPanel.Loaded on FacebookLogin.xaml, I can use the following code to

How to handle exceptions thrown by Tasks in xUnit .net's Assert.Throws<T>?

試著忘記壹切 提交于 2020-01-21 02:37:05
问题 The following asynchronous xUnit.net test with a lambda marked with the async modifier fails by reporting that no exception was thrown: [Theory, AutoWebData] public async Task SearchWithNullQueryThrows( SearchService sut, CancellationToken dummyToken) { // Fixture setup // Exercise system and verify outcome Assert.Throws<ArgumentNullException>(async () => await sut.SearchAsync(null, dummyToken)); // Teardown } To make sure that an ArgumentNullException is actually thrown I explicitly used a

How to wait for async method to complete?

耗尽温柔 提交于 2020-01-18 05:47:46
问题 I'm writing a WinForms application that transfers data to a USB HID class device. My application uses the excellent Generic HID library v6.0 which can be found here. In a nutshell, when I need to write data to the device, this is the code that gets called: private async void RequestToSendOutputReport(List<byte[]> byteArrays) { foreach (byte[] b in byteArrays) { while (condition) { // we'll typically execute this code many times until the condition is no longer met Task t =