I tend to call this pattern the "GatedBatchWriter", i.e. the first thread through the gate handles a batch of tasks; its own and a number of others on behalf of other writers, until it has done enough work. This pattern is primarily useful, when it is more efficient to batch...

I got it working. It was the structure of the code (not included in my question) that was leading to this. The fact that it's a Web Forms app is also appears to be a factor. The original code looked like this: protected void Button1_Click(object sender, EventArgs e) { var...

Using the comments on my question, especially the note about the continuation method which made me find this very useful question, I achieved the following: The first part of initialization is performed asynchronously (no change). The second part of the initialization (which creates the UI elements) is performed afterwards as...

As you suspected, the catch block won't get any exceptions since you didn't synchronize with current context. In order to do that you have to mark your action method as async and use await for calling SendSalesEmailsAsync. So the action method will look like this: public async Task PerformCheckout(int salesAddressId)...

If you want an immediate notification similar to what a cancellation gives you but without an exception you can simply use TaskCompletionSource. TaskCompletionSource is how you create a promise task. You get an uncompleted task from the Task property and you complete it (or cancel) with SetResult. You can use...

The problem is that you're consuming the only available UI thread in you button1_Click(). Presumably, your UI is also frozen indefinitely. When you use async/await, then execution of the continuation - in your case, the line Console.WriteLine(myString); - will continue in the same synchronization context as the original function was...

When I return from that call and try to call base.LogEvent(), I get an ObjectDisposedException stating that "Safe Handle has been Closed". That's because somewhere higher up the call-chain, someone is disposing your plugin object, which hasn't really finished the asynchronous operation. Using async void is doing a "fire...

The actual answer is too long to post here. Short answer No, you should not call async methods from sync methods. The method tree should be asynchronous bottom to top. For example: Using ASP.NET MVC async methods would be called from async Action methods, see: Using Asynchronous Methods in ASP.NET...

You can't use await in a constructor. There are several things you can do instead. The best here IMO is to have a separate async method that you call and await after you create the object. var listAdapter = new CustomListAdapter(this); await listAdapter.InitializeAsync(); Another option is to make the constructor...

Do these have the same result? Edit: @Servy points out correctly that since the ContinueWith is simply a projection of the result. This means that both operations are semantically equivalent, but exception wise they'll behave differently. Are there any advantages to either approach? Is there a better way to...

When you mark a method as async Task<string> you are telling the consumer of it that the method promises to return you a string in the future. I think you're getting hung up on the await keyword. The await keyword allows you to pause execution of your method until the...

below is a full example. you can run the ReserverAHoliday both Synchronously (bool r = ReserveAHolliday().Result;) and Asynchronously (just call ReserveAHolliday();) from MAIN (depends which line you comment). and you can see the effect ("END" gets printed before / after the reservation is complete). I prefer the await Task.WhenAll() methods,...

I suspect that further up your call stack, your code is calling Task<T>.Result or Task.Wait. This will deadlock your application. The appropriate solution is to replace all calls to Result or Wait with await. More info in my MSDN article on async best practices or my blog post that deals...

As the MSDN page on Task<T> explains, all exceptions thrown by a Task are wrapped in AggregateException before being thrown to the awaiting code. If you're using multiple levels of async/await and not catching this exception at the lowest possible level, then each time it bubbles up another level, it'll...

You are not using async/await in a foreach loop, you are using async/await with List<T>.ForEach(Action<T>). Because ForEach only accepts Action<T> (void return type) your ForEach(async d => { ... } is being processed as a async void function because that is the only way for it to be passed in...

The async equivalent is a while loop with Task.Delay (which internally uses a System.Threading.Timer): public async Task PeriodicFooAsync(TimeSpan interval, CancellationToken cancellationToken) { while (true) { await FooAsync(); await Task.Delay(interval, cancellationToken) } } It's important to pass a CancellationToken so you can stop that operation when you want (e.g. when you...

In that case I've first task loaded then second with no parallelism...how can I optimize this? You want concurrency, not parallelism. Instead of awaiting each task sequentially, you can await on them both using Task.WhenAll: public async Task LoadAsync() { IsBusy = true; var firstDropDownItemsTask = repository.LoadStates(); var secondDropDownItemsTask...

Use TaskCompletionSource. That's how you create an asynchronous task and complete it when you want. Create it when a call is made to GetAffirmative, await its Task property and complete it instead of setting a false to blocked: alert.SetOnDismissListener(new OnDismissListener(() => { _tcs.SetResult(false); })); ... TaskCompletionSource<bool> _tcs; private async Task<bool>...

Task.Factory.StartNew doesn't recognise async delegates as there is no overload that accepts a function returning a Task. This plus other reasons (see StartNew is dangerous) is why you should be using Task.Run here: tasks.Add(Task.Run(async () => ... ...

Your definition of RetryTest accepts a T and then returns a ServiceResponse<T> When you call it you've supplied: ServiceResponse<DataJob> as T, so the return type of RetryTest, since it needs to wrapT in a ServiceResponse, should return a ServiceResponse<ServiceResponse<DataJob>> rather than a ServiceResponse<DataJob>. (You're not returning that, hence the error.)...

The defect is here: var id = CreateDocument("My Title").Result; As I explain on my blog, you should not block on async code. Instead of Result, use await: var id = await CreateDocument("My Title"); ...

There are two general methods to achieve what you wanted: Use ConfigureAwait(false) in your async library. In your case you should do it inside GetLatestPlaces() method. Call you async method in a different thread in order to not block the current context. So your code will look like this: IList<PlaceListItemViewModel>...

But the Task never finishes Because both examples synchronously block, causing your code to deadlock. You shouldn't be blocking on async code. You'll need to properly asynchronously wait on HandleSignalRAsync: await Functions.HandleSignalRAsync().ConfigureAwait(false); If you're already using async-await, there's no advantage to use a continuation style with ContinueWith, you can...

Getting Stephen Cleary's IAsyncCommand pattern working with functions that take a parameter when producing the Task to be executed would require just a few tweaks to his AsyncCommand class and static helper methods. Starting with his classes found in the AsyncCommand4 sample in the link above, let's modify the constructor...

You are not waiting for your task so your application ends before the task has a chance to complete. You need to Wait or await it (which you can't do in Main but should do anywhere else). static void Main(string[] args) { MockAPI api = new MockAPI(); Task t =...

Aren't async methods meant for this kind of things? No, async doesn't change the HTTP protocol. You still only have one response per request, and that response can only be sent once. async will free up the calling thread, but on ASP.NET this just means that the thread is...

You can achieve that with AsyncBridge. E.g. using (var asyncBridge = AsyncHelper.Wait) { asyncBridge.Run(DoWorkAsync()); } It works by installing a custom SynchronizationContext and using that to wait for the task whilst freeing the UI thread. Because it is using synchronization context rather than using the dispatcher directly it is essentially...

Can anyone provide any kind of authoritative information as to whether the old BeginRead limitation still applies to ReadAsync or not? The same limitations apply for BeginRead and ReadAsync. The old APM methods haven't been deprecated. They are still fully supported and there's nothing wrong with using them. However,...

Is this described behaviour right ? Yes. Is it correct ? Yes. is the DoSomeHeavyWork processed inside task1 or where (where it is "awaited") ? I think this a key question. From the current code, DoSomeHeavyWork will asynchronously wait for Task.Delay to complete. Yes, this will happen on the...

There are many possible designs for this. But I always prefer TPL Dataflow. You can use an ActionBlock and post async delegates into it to be processed sequentially: ActionBlock<Func<Task>> _block = new ActionBlock<Func<Task>>(action => action()); block.Post(async () => { await Task.Delay(1000); MessageBox.Show("bar"); }); Another possible solution would be to asynchronously...

Is it the best practice to call it from the current thread as shown? If your current thread is free while the async operating is on going, why use a different thread? What would make that thread better than the one you're already using? Question comes to mind concerning...

An async method returns when after encounters an await statement and sets up the asynchronous operation being awaited. The rest of the method then continues after the await is finished. You probably can't step through async methods like that, but try putting a breakpoint after the await and it should...

I don't think you need asyncbecause you are not waiting for the result. Your method is CPU bound you can push it to the background with Task.Run if you want to execute it on the thread pool or Task.Factory.StartNew( () => /*..*/, TaskCreationOptions.LongRunning) if you want a dedicated thread. public...

I wouldn't do this on the server side as one have to be careful which waiting calls to use to avoid high resource consumption under load. Your users also don't get any feedback from the page. You can improve this situation by displaying a spinning wheel, but it might be...

When overriding a method it must have the same signature as the original method of the base class (or an interface / abstract class). I would imagine based on this question the expected behavior of Seed() is a synchronous operation. Therefore it's not a good idea to override it and...

Your understanding is correct. Don't use async void though, there is no need. Use async Task and be sure to process errors. Right now you will never find out about bugs causing crashes. Will the controller action method return control back to the browser even though the DeliverAsync method is...

The reason you're seeing this is because your method is async void which executes in a "fire and forget" fashion, so you're seeing the value returned by the instansiation of the response message, not the response of PostAsync. Don't expose a single class HttpResponseMessage field, it may be stale if...

You say in your comment that the exception you are getting is a LockRecursionException. This means that somewhere either: A thread is hitting EnterWriteLock while that thread already has a write lock, and the lock was not created with LockRecursionPolicy.SupportsRecursion. Don't create it with LockRecursionPolicy.SupportsRecursion; recursive locks are always a...

This: RunAsyncBlogs().Wait(); Is deadlocking your code. It is synchronously blocking your async method call which is trying to marshal back the continuation on to the implicitly captured synchronization context. That is why you shouldn't block on async code protected async void btnLoadData_Click(object sender, EventArgs e) { // Other stuff await...

GetSchoolyearsAsync is an async method, so it returns a Task<IEnumerable<SchoolyearDTO>> and not just a IEnumerable<SchoolyearDTO>. You need to specify that in the type parameters for SetupGet mockService.SetupGet<Task<IEnumerable<SchoolyearDTO>>>(c => c.GetSchoolyears()). Returns(Task.FromResult(Enumerable.Empty<SchoolyearDTO>())); ...

The events are all fired in order. If your event handlers are asynchronous, which seems to be the case, then the code firing the events is going to continue executing as soon as it starts the event handlers, not when they complete. If the code firing the events needs to...

client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate"); With this you tell the server that you allow it to compress the response gzip/deflate. So the response is actually compressed which explains why you get the kind of response text you get. If you want plain text, you shouldn’t add the header, so the server won’t...

You shouldn't be using Task.Factory.StartNew with async-await. You should be using Task.Run. Task.Factory.StartNew came in .Net 4.0 without async-await in mind. You can still use it, but unless you have a good reason, Task.Run is a safer alternative. Instead of returning a Task it returns a Task<Task> that you need...

Entity Framework can not handle multiple concurrent requests using a single DbContext. You need to await each list before you move on to the next one or use 3 separate DbContexts. Here is how to do it just awaiting each request individually. public async Task<ActionResult> Load() { var housing =...

If you are trying to test the service, I think you should avoid testing the proxy code and WCF access altogether - they add unnecessary complexity to the test meaning you're testing much more than you intended to. Just construct your service in your test method or test initialisation method,...

This appears to be a case of the classic ASP.NET deadlock. Don't do sync over async. If you must do it use a safe workaround for the deadlock such as: Task.Run(() => SomethingAsync()).Result Note, that this is not helpful to efficiency but it's not a major issue if this piece...

but now when I run the dll by clicking the button, I cannot navigate the UI Task != Thread. A task may or may not use a thread to do it's work. When you use: var scheduler = TaskScheduler.FromCurrentSynchronizationContext(); You're telling the task factory to execute the given delegate...

the Funcation is using async keyword but does not await for anything in it's body so it will always run synchronously. also Function does not even compile. A) Task.Factory.StartNew(() => Funcation(1, 1)); //Runs Async here you create a thread and on that thread you call Function so it is asynchrounsly...

Why the public async Task DoStuff() method below can still work without returning anything? Because the compiler allows it to. When you mark a method with the async modifier, a state-machine is created which actually returns a Task for you. You can see it in any de-compiler. When I...

I also need to roll back previous things if something breaks, like remove a database row if the email fails to send, so there are a few levels of try/catches in there. You'll find that async/await (paired with Task.Run instead of StartNew) will make your code much cleaner: var...

You can't, and shouldn't. PLINQ isn't for database access. The database knows best on how to parallelize the query and does that just fine on it's own using normal LINQ. PLINQ is for accessing objects and such where you are doing computationally expensive calculations within the LINQ query so it...

This turns out to be a property of TaskExtensions.WithCurrentCulture. These are the docs for EF, but they apply for ASP.NET Identity as well: Configures an awaiter used to await this Task to avoid marshalling the continuation back to the original context, but preserve the current culture and UI culture. This...

You seem to be interested in using async for fan-out parallelism. That's a totally valid thing to do. It is not necessary to make the entire call chain async to make use of fan-out parallelism. You stumbled over the usual ASP.NET deadlock. You can use Task.Run as a simple, fail-safe...

task.Wait(); is redudant, the call to task.Result would wait implicitly. Here is your method rewritten to use await. Task<Repository> task = client.Repository.Get("openEHR", "CKM-mirror"); var myResult = await task; return myResult.FullName; You don't need .Result either as the type of await on a Task<T> is T. On the subject of exception...

You have to await the save otherwise the method will continue and your context would go out of scope before saving changes. You have to make the method asynchronous, too. public **async** Task<ActionResult> IncrementRefreshcounter(int id) { using ( var context = new MyDBContext()) { //at each page refresh i would...

When you call an async method you should await the returned task, which you can only do in an async method, etc. Awaiting the task makes sure you continue execution only after the operation completed, otherwise the operation and the code after it would run concurrently. So your code should...

If I understand your question correctly, it boils down to this: How do I start a long running task from an API call but respond before it is finished. Short Answer: You don't in the API. You delegate to a Service. Long Answer: The error you are getting is most...

I worry that my previous answer wasn't quite what you want. What I supplied just got you through the compile error. But one thing about it, is that it does not run asynchronously. Task.Wait and Async.RunSynchronously will both block the running thread until the operation is complete. If you want...

must a unit test for an async method call that async method asynchronously? No, but it is most natural to do so. If it calls the async method synchronously using Task.Run(), what is lost? Nothing really. It's slightly less performant, but to a degree that you will probably never...

In normal procedural code, this wouldn't be a problem. The whole point of async/await is to write asynchronous code in a way that looks practically identical to "normal" synchronous code. Being fairly new to the async/await stuff, I'm not sure the ramifications on the rest of my code ......

If you await the task then the rest of the method is executed as a continuation of that Task and control is returned to the caller of the current method, so yes, it'll be asynchronous. That is the point of await after all; to behave asynchronously. Calling Result on an...

The question is too broad so the answer is generic. In order "to write a csv file and an XML file at the same time" you have to implement sort of multi-threading, using either Task Parallel Library (TPL - recommended) or other technique available in .NET, and run the aforementioned...

First, what's special about this exception is that it's being thrown from Task.Run and for that scope, the exception really isn't handled by user-code. The framework catches and stores the exception in the returned task for you to handle later, if you fail to do that it's an unobserved task...

Is using SemaphoreSlim the correct way to replace a lock statement in an async method? Yes. Should I make the cacheMissResolver argument of type Func<Task<Thing>> instead? Yes. It'll allow the caller to provide an inherently asynchronous operation (such as IO) rather than making this only suitable for work that...

Finally I find a solution of the problem. I am not sure if it is a best practice or not, but it works in my case. If someone has better idea to improve my solution, please let me know. The background worker: private static void StartListening() { _dataLength = (_dataLength...

This isn't single threaded. When the delay task completes the rest of the method is posted to the ThreadPool and runs concurrently with your main thread. The "trigger" here is the callback of the internal System.Threading.Timer being used inside Task.Delay. This behaviour depends on the SynchronizationContext. In a UI environment...

This isn't doing what you think it is: await Task.Run(() => LongProcess()); The code is awaiting Task.Run(), but nothing within that task is awaiting LongProcess(). So Task.Run() returns immediately in this case. This is actually an interesting illustration of a failure to be "async all the way down", because the...

Assuming the unit-testing framework is async-aware (if you are doing asynchronous unit testing, one hopes it is :) ), then you should be able to just fix your compiler error: [TestMethod] public async Task MethodToBeTestedSuccess() { List<int> results = await MethodToBeTested() ...... } In other words, given the signature you...

I am not "yielding" back to the thread function The method yields once hitting await udpc.ReceiveAsync(), that is how async-await works. ListenAsync itself synchronously blocks, but since there is no sync context that comes into play, the continuation is able to marshal itself onto an arbitrary thread pool thread....

TransformBlock already maintains FIFO order. The order in which you post items to the block is the exact order in which the items will be returned from the block. When you specify a maximum degree of parallelism that is larger than 1, multiple messages are processed simultaneously, and therefore, messages...

As mentioned by Alexei Levenkov above, I was causing a deadlock using the getDataAsync().Result code. While mapping my Place object to a MapPlaceDTO object, the Place object has a get property to load the place type, which would call an async function in the following way: public PlaceType PlaceType {...

Simply await the task returned from WhenAny. If it's faulted, it'll unwrap the exception and throw it, if it didn't, you know it's already done, so you can continue on. Alternatively, you could simply call Unwrap on Task.WhenAny and then await that. This would be semantically identical to the previous...

Each async method gets its own state-machine and task, you can't automagically combine them. You can remove both the async and await and use Task.ContinueWith which removes the state-machine, but it does still create a new task: public Task<ClaimsIdentity> CreateIdentity(string userid ) { Guid gid = Guid.Parse(userid); return _dbContext.Users.Where(d =>...

As it has been pointed by @Servy it is a non-deterministic behaviour - I was unable to get it not printed on my machine, you were unable to get it printed on yours. Why is it non-deteministic? Because: Tasks are created as background threads Console has no synchronization context That...

Why your code for ConvertToBase64 isn't being awaited? This is completely wrong, as the async void construction. Try to change your code to something like this: newOffer.photoBase64 = await SetPhotoString(Photo);//this line throws an excp. public async Task<string> SetPhotoString(BitmapImage bi) { return await bi.ConvertToBase64(); } Also, what line of the ConvertToBase64...

I'm assuming there's some syntactic sugar involved here Not exactly "syntactic sugar". The compiler is generating a state-machine as the method was marked as async. That is why you can return a Task<bool> without explicitly creating a Task for the return value. If I leave off the async keyword,...

is Log also awaited by the await call on Create? No, it isn't. Log will pass through and the encapsulated task it produces will be ignored (along with any exception it propagates). Because you end up returning the task from CreateAsync, that will be awaited....

System.Net.ServicePointManager.Expect100Continue = false; That one line of code in our case fixed the problem. A developer from a different team offered that suggestion, and it works. I have yet to google it and read up on it enough to offer an explanation of what that is addressing. ...

This is pretty normal, COM will pump when the call crosses an apartment boundary. It has to pump, not doing so is very likely to cause deadlock. It is unclear why that boundary has to be crossed from the snippet, it looks like an STA thread when you talk about...

I think the core misunderstanding is around the Task type. In asynchronous code, a Task is always already running. So this doesn't make sense: Is there a non-blocking Task.WaitAll similar to Task.WhenAll but not parallel concurrent? If you have a collection of tasks, they're all already started. I want to...

Stephen toub's article says that exposing asynchronous wrappers for synchronous methods in a library is bad. That adds no value. If the developer wants, he can always call Task.Run(()=> SomeSynchronousMethod());. There is no need to expose it in a library. If it is an application, yes you can, because that...