async-await

Are the SmtpClient.SendMailAsync methods Thread Safe?

亡梦爱人 提交于 2019-12-19 03:22:15
问题 The SmtpClient Class states that instance members are not thread safe. This can be seen if concurrent calls are made to Send or SendAsync. Both methods will throw a InvalidOperationException on the second call if the first has not yet completed. The method SendMailAsync, introduced in .NET 4.5, does not list InvalidOperationException as a thrown exception. Do the new .NET 4.5 methods implement some sort of queuing? Reflector isn't able to shed any light on the implementation details of this

How do I yield a sequence of promises from an async iterator?

给你一囗甜甜゛ 提交于 2019-12-19 03:20:34
问题 I start with a function which renders and yields a sequence of image blobs. async function* renderAll(): AsyncIterableIterator<Blob> { const canvases = await getCanvases(); for (const canvas of canvases) { yield await new Promise<Blob>((resolve, reject) => { canvas.toBlob(result => { if (result) resolve(result); else reject(); }); }); } } That works fine, but the performance isn't ideal because each promise has to be resolved before starting on the next operation. Instead, the caller should

What's the best way to wrap a Task as a Task<TResult>

牧云@^-^@ 提交于 2019-12-19 02:46:27
问题 I am writing some async helper methods and I have APIs to support both Task and Task<T> . To re-use code, I'd like the Task -based API to wrap the given task as a Task<T> and just call through to the Task<T> API. One way I can do this is: private static async Task<bool> Convert(this Task @this) { await @this.ConfigureAwait(false); return false; } However, I'm wondering: is there there is a better/builtin way to do this? 回答1: There is no existing Task method that does exactly this, no. Your

Thread.Sleep(2500) vs. Task.Delay(2500).Wait()

二次信任 提交于 2019-12-19 02:39:21
问题 I want some clarity on this. I know that Task.Delay will internally use a Timer and it is obviously task-based (awaitable), whereas Thread.Sleep will cause the thread to be blocked. However, does calling .Wait on the task cause the thread to be block? If not, one would assume that Task.Delay(2500).Wait() is better than Thread.Sleep(2500) . This is slightly different that the SO question/answer here as I'm calling .Wait() . 回答1: Using Wait on an uncompleted task is indeed blocking the thread

How to return empty IQueryable in an async repository method

女生的网名这么多〃 提交于 2019-12-19 02:26:31
问题 Lets say I have a simple repository class, with one GetByNames method public class MyRepo { private readonly MyDbContext _db; public MyRepo(MyDbContext db) { _db = db; } public IQueryable<MyObject> GetByNames(IList<string> names) { if (names== null || !names.Any()) { return Enumerable.Empty<MyObject>().AsQueryable(); } return _db.MyObjects.Where(a => names.Contains(a.Name)); } } Now when I use it with async EntityFramework ToListAsync() extension var myObjects = awawit new MyRepo(_db)

Is it OK to use async/await almost everywhere?

故事扮演 提交于 2019-12-19 02:07:09
问题 I'm currently writing small NodeJS CLI tool for personal usage and I've decided to try ES7 async/await feature with Babel. It's a network tool so I obviously have asynchronous network requests. I wrote a simple wrapper for request package: export default function(options) { return new Promise(function(resolve, reject) { request({...options, followAllRedirects: true, headers: { "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0" } }, (error, response, body

Task.WhenAll not waiting

 ̄綄美尐妖づ 提交于 2019-12-19 02:05:19
问题 I am learning how to use async functions in console application but can't make the Task.WhenAll wait until all tasks are completed. What is wrong with the following code? It works synchronously. Thank you in advance. static void Main(string[] args) { ... IncluiValores(...); ... } static async void IncluiValores(...) { Task<List<int>> res1 = att.GetAIDBAPI(att); Task<List<int>> res2 = att.GetAIDBAPI(att2); List<int>[] res = await Task.WhenAll(res1, res2); ... } UPDATE - Function Definition:

Race Condition in Async/Await Code

两盒软妹~` 提交于 2019-12-18 21:49:30
问题 I just wonder whether a race condition occurs in the code below: int readingFiles; async Task<string> ReadFile (string file) { ++readingFiles; var text = await Stream.ReadFileAsync(file); --readingFiles; return text; } If ReadFile method is executed by a thread pool thread, readingFiles will be accessed by two different threads and the readingFiles variable is not protected by any synchronization idioms. It means that the first update to readingFiles should not be visible to the other thread

How to deal with side effects produced by async/await when it comes to mutable value types?

余生颓废 提交于 2019-12-18 20:13:31
问题 Please, consider the following example code: using System.Diagnostics; using System.Threading.Tasks; public struct AStruct { public int Value; public async Task SetValueAsync() { Value = await Task.Run(() => 1); } public void SetValue() { Value = 1; } } class Program { static void Main(string[] args) { Test(new AStruct()); TestAsync(new AStruct()).Wait(); } private static async Task TestAsync(AStruct x) { Debug.Assert(x.Value == 0); await x.SetValueAsync(); Debug.Assert(x.Value == 0); }

how to manage an NDC-like log4net stack with async/await methods? (per-Task stack?)

青春壹個敷衍的年華 提交于 2019-12-18 19:00:22
问题 In a normal/synchronous/single-threaded console app, NDC.Push works fine for managing the 'current item' (potentially at multiple levels of nesting, but just 1 level for this example). For example: private static ILog s_logger = LogManager.GetLogger("Program"); static void Main(string[] args) { BasicConfigurator.Configure(); DoSomeWork("chunk 1"); DoSomeWork("chunk 2"); DoSomeWork("chunk 3"); } static void DoSomeWork(string chunkName) { using (NDC.Push(chunkName)) { s_logger.Info("Starting to