Menu
  • HOME
  • TAGS

SendMailAsync : An asynchronous module or handler completed while an asynchronous operation was still pending

c#,asp.net-mvc,async-await,task-parallel-library,smtpclient

Your call hierarchy is broken. You shouldn't use async void, that is ment for event handlers only, use async Task instead: public static Task SendEmailAsync(MessageContent messageContent, string emailBody) { SmtpClient smtpClientNoSend = new SmtpClient(); return smtpClientNoSend.SendMailAsync(mailMessage); } public async System.Threading.Tasks.Task<ActionResult> Register() { await SendEmailAsync(); } private Task SendEmailAsync() { return...

Proper way to handle a group of asynchronous calls in parallel

c#,parallel-processing,async-await,task

Change this: foreach(var service in services) { Console.WriteLine("Running " + service.Name); var _serviceResponse = await client.PostAsync(_baseURL + service.Id.ToString(), null); Console.WriteLine(service.Name + " responded with " + _serviceRepsonse.StatusCode); } to this: var serviceCallTaskList = new List<Task<HttpResponseMessage>>(); foreach(var service in services) { Console.WriteLine("Running " + service.Name); serviceCallTaskList.Add(client.PostAsync(_baseURL + service.Id.ToString(), null)); } HttpResponseMessage[]...

Task.StartNew() works differently on STA mode?

c#,wpf,multithreading,async-await,task-parallel-library

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...

HttpClient.PostAsJsonAsync never sees when the post is succeeding and responding

c#,async-await,dotnet-httpclient,connection-timeout

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. ...

Async/Await handling group of HttpResponseMessage

c#,asynchronous,async-await

I'm suggesting this without trying it out so please be careful but I would replace these two lines: var responses = await Task.WhenAll(members.Select(x => PostMemberAsync(x,_client))); await Task.WhenAll(responses.Select(r => ProcessResponseAsync(r,client))); with this: await Task.WhenAll(members.Select(async x => { var response = await PostMemberAsync(x, _client); await ProcessResponseAsync(response, client, x); })); And of course...

Throwing exception from Task.Run displays “Not Handled from User Code” Message

c#,.net,async-await,task-parallel-library

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 it incorrect to call async methods synchronously in unit tests?

c#,unit-testing,asynchronous,async-await,typemock-isolator

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...

Correct use of async and await

c#,async-await

Let's take them one at a time: public async Task WriteFile() { string filePath = @"SampleFile.txt"; string text = txtContents.Text; Task task1 = new Task( () => WriteTextAsync(filePath, text)); } What's task1 doing here? You need to actually have run it and await on it: public async Task WriteFile() {...

Invoking synchronous method asynchronously completes task faster than natural async methods [closed]

c#,async-await,task-parallel-library

You aren't actually measuring anything. Task.WhenAll(tasks); returns a Task of the completion of all of those tasks. You don't do anything with that task, so you aren't waiting for anything to finish. Therefore, you're just measuring the synchronous initialization of each alternative. Task.Run() just queues a delegate to the thread...

Testing an asynchronous WCF service using MSTest

c#,.net,wcf,async-await,mstest

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,...

Combine Results from Async Method and Return Synchronously

c#,azure,asynchronous,async-await

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...

Write async method correctly

c#,asynchronous,methods,async-await,task-parallel-library

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...

Wait IAsyncResult function until complete

c#,.net,asynchronous,async-await,iasyncresult

I dont have any idea what is the goal of this method _contactGroupServices.BeginDeleteContact . But lets try to write template for it Func<object> doWork = () => { return _contactGroupServices.BeginDeleteContact(<your parameters>) }; AsyncCallback onWorkDone = (ar) => { //work done implementation }; IAsyncResult asyncResult = doWork.BeginInvoke(onWorkDone, null); asyncResult.AsyncWaitHandle.WaitOne(); var result...

Async task raises NotImplementedException

c#,windows-phone-8.1,async-await,.net-4.5

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...

SaveChangesAsync not updating value in database table

c#,asp.net-mvc,entity-framework,async-await

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...

await Task vs await Task.Run(voidMethod)

c#,asynchronous,async-await

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...

Async void method in Console doesn't want to fire

c#,console,async-await

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...

How to await a ParallelQuery with LINQ?

linq,asynchronous,async-await,parallel-extensions

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...

Writing/Reading To/From File Windows 8.1 AppStore App

c#,async-await,windows-applications

I tried doing ms-app in stead of ms-appdata and it fixed that error. Thank you for your help.

If an async method is single threaded how can it be run in the background?

c#,.net,multithreading,asynchronous,async-await

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...

Implicit awaiting?

c#,asynchronous,async-await

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....

Mock async Get method with MOQ

c#,.net,async-await,moq

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>())); ...

Are Stream.ReadAsync and Stream.WriteAsync supposed to alter the cursor position synchronously before returning or after the operation completes?

c#,stream,async-await,filestream,c#-5.0

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,...

How to handle async & await with default override's

c#,android,asynchronous,xamarin,async-await

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...

C# Async method call all the way to Main

c#,async-await

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,...

Confusion about calling CPU-bound methods synchronously from an async method

c#,asp.net,.net,async-await,task-parallel-library

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...

ActionNameAsync-ActionNameCompleted vs async-await in Asp.NET MVC

c#,asp.net,asp.net-mvc,asynchronous,async-await

The "main difference" is that the Async/Completed approach is using an outdated and less maintainable way to do asynchronous request handling.

WCF WebMethod with a blocking call

c#,wcf,async-await

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...

How to catch an OperationCanceledException when using ContinueWith

c#,asynchronous,.net-4.0,async-await

Cancellation is handled differently from other exceptions. Basically, you can use this pattern: Task.Factory.StartNew(() => { // The task }, tokenSource.Token) .ContinueWith(task => { // The normal stuff }, TaskContinuationOptions.OnlyOnRanToCompletion) .ContinueWith(task => { // Handle cancellation }, TaskContinuationOptions.OnlyOnCanceled) .ContinueWith(task => { // Handle other exceptions }, TaskContinuationOptions.OnlyOnFaulted); Or the alternative...

Possibility of Semaphoreslim.Wait(0) (to prevent multiple execution) causing non execution

c#,asynchronous,async-await,semaphore

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...

Losing HttpContext with async await in ASP.NET Identity GetRolesAsync

c#,asp.net-web-api,async-await,asp.net-identity

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...

C# async await simple issue

c#,asynchronous,async-await

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...

MVC App - Is this the correct approach for using Async and Await?

c#,asp.net-mvc,async-await

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)...

ASP.NET and async - how it works?

asp.net,asp.net-mvc,async-await,task-parallel-library

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...

Run async method regularly with specified interval

c#,asp.net,.net,multithreading,async-await

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...

Using asyn await in foreach loop

c#,async-await,task-parallel-library

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...

Unable to use result of Async DocumentDB operation CreateDocumentAsync

c#,azure,async-await,task-parallel-library,azure-documentdb

That's because you're not awaiting an asynchronous method: This: var doc = _applicationResource.Save(data); Needs to be: var doc = await _applicationResource.Save(data); Your method should look as follows: [HttpPost] [Route("")] public async Task<IHttpActionResult> CreateNewApplication(dynamic data) { if (data == null) { return BadRequest("data was empty"); } try { var doc =...

Why does the method return a string when return type is Task?

c#,.net,asynchronous,async-await

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...

Not getting the hang of TASKs and WAIT in C#

c#,asynchronous,async-await,task

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...

Using ConfigureAwait(false) on tasks passed in to Task.WhenAll() fails

c#,asynchronous,async-await

You only need ConfigureAwait when you actually perform the await, the correct form would be [HttpGet] public async Task<JsonResult> doAsyncStuff() { var t1 = this.service1.task1(); var t2 = this.service2.task2(); var t3 = this.service3.task3(); var t4 = this.service4.task4(); await Task.WhenAll(t1,t2,t3,t4).ConfigureAwait(false); return this.Json(new {redirect = true, href = Url.Action("Blah")}, JsonRequestBehavior.AllowGet); } ...

Async and Await - Will control return immediately from an MVC action method?

c#,asp.net-mvc,async-await

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...

How does control flow remain in the async method scope after it has returned the result? Is this similar to closure for variables?

c#,.net,async-await,task-parallel-library

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...

Function Running Sync When VS Says it should be running async

c#,.net,async-await

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...

What circumstances other than “await” will allow synchronous code to be interrupted

c#,com,async-await,activex,rcw

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...

ObjectDisposedException when trying to access Thread.CurrentPrincipal with async method

c#,multithreading,asynchronous,async-await

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...

How to handle exceptions when using Task Parallel Library Task.WhenAny()

c#,async-await,task-parallel-library,c#-5.0

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...

Unable to await method in ASP.NET (4.6) MVC5 project

c#,asp.net,unit-testing,asp.net-web-api,async-await

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 {...

Triggering events from async/await functions in the right order

c#,events,design-patterns,asynchronous,async-await

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...

Using the result of an async method

c#,asynchronous,async-await

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...

Using HttpClient.GetAsync to call Web API seems to hang

c#,asp.net,asp.net-web-api,async-await,task-parallel-library

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...

.Net Task class - please explain

c#,.net,asynchronous,async-await,task

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...

Array of async tasks. Can I attach metadata to each task?

c#,.net,asynchronous,async-await

Yes you are doing this wrong. The point of async await is to maintain simple control flow, whilst running your code asynchronously. var tasks = users.Select(async user => { var products = await this.repository.GetProducts(user.UserName); return new { user, products }; }); var results = await Task.WhenAll(tasks); var resultsAsDictionary = results(x...

How can I test a method with a Task return type?

c#,unit-testing,async-await,task

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...

await/async odd behaviour

c#,.net,asynchronous,async-await,task-parallel-library

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 =...

Implementing SendBatchAsync for Microsoft Azure Service Bus Brokered Messages

c#,azure,async-await,azureservicebus,brokeredmessage

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...

Run async method in overridden void

c#,asp.net,asp.net-mvc,asp.net-mvc-5,async-await

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>...

Can requests be handled on a separate thread?

asp.net-mvc,multithreading,async-await,httprequest

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...

Asynchronous MVVM commands

wpf,asynchronous,mvvm,async-await,task-parallel-library

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...

Task.Factory.StartNew with async lambda and Task.WaitAll

c#,.net,async-await,task-parallel-library

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 () => ... ...

ASP.NET call hangs on async await

asp.net,async-await,iis-express

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"); ...

Is Task.Run or Task.Factory.StartNew are bad practice for windows phone or any other client platform?

c#,.net,windows-runtime,windows-phone,async-await

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...

how to update multiple data in entityframework through async web api

entity-framework,asp.net-web-api,async-await,web-api,asp.net-web-api2

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...

How to 'await' a listener properly? Replacing a hacky spin-lock solution

c#,xamarin,async-await

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>...

Why Do I Need To Make This Method Async? [duplicate]

c#,asynchronous,async-await,task-parallel-library

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,...

Method to handle exceptions in a async block to cannot convert return object to to async method return type

c#,async-await

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.)...

Async/Await in foreach with HTTPClient

c#,asynchronous,async-await

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 ......

Merge asyc method into one task

c#,.net,asynchronous,async-await

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 =>...

C# Cannot replace void with async Task

c#,async-await

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...

async await for a HttpClient.PostAsync call

c#,asynchronous,async-await,dotnet-httpclient

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...

HttpClient returning special characters but nothing readable

c#,wpf,async-await,httpclient

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...

Async operations and UI update

c#,wpf,multithreading,async-await,caliburn.micro

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...

WPF calling asynchronous code with out locking on Task..WhenAny()

c#,.net,wpf,async-await,.net-4.5

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...

Windows Phone 8.1 - HttpClient SendRequestAsync will never return with a response

c#,.net,windows-phone-8.1,async-await

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...

Async await usage for MongoDB repository

c#,mongodb,asynchronous,parallel-processing,async-await

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...

Potential cause for ExecuteReaderAsync to lose context

c#,async-await,task-parallel-library

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...

Implementing async version of a sync method: How to return Task which is constant 1?

c#,.net,async-await

Use return Task.FromResult(1); ...

Task await fails

c#,asynchronous,async-await,signalr,task

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...

Guarantee TransformBlock output sequence

c#,multithreading,async-await,task-parallel-library,tpl-dataflow

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...

Async Controller not returning anything to the view when querying multiple datatable in parallel

c#,entity-framework,asp.net-mvc-5,async-await

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 =...

Running c# async method in f# workflow

f#,async-await,c#-to-f#

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...

Why async code is run on worker thread in C#

c#,multithreading,asynchronous,async-await

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....

How to setup multiple async methods into a queue?

c#,.net,queue,async-await,.net-4.5

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...

Sequential version of Task.WhenAll

c#,async-await

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...

Call to C# async method doesn't return in Web Application [closed]

c#,async-await

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...

Correct way to convert method to async in C#?

c#,asynchronous,async-await

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...

How async works understood correctly?

async-await

Correct, the method can't continue until the awaited asynchronous operation is complete.

Implication of calling result on awaited task

c#,.net,asynchronous,async-await

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...

ConfigureAwait for IObservable

c#,asynchronous,async-await,system.reactive

You have to comprehend what "awaiting an Observable" means. Check out this. So, semantically, your code await this.service.Receiver .FirstOrDefaultAsync(x => x == "foo") .Timeout(TimeSpan.FromSeconds(1)); is equivalent to await this.service.Receiver .FirstOrDefaultAsync(x => x == "foo") .Timeout(TimeSpan.FromSeconds(1)) .LastAsync() .ToTask(); (Note that there is some kind of redundance here, calling FirstOrDefaultAsyncand LastAsync but...

cancel task.delay without exception or use exeption to controll flow?

c#,asynchronous,exception-handling,async-await,task-parallel-library

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...

Can this async/await code be rewritten using Task.WhenAll(…) or something else that makes more sense then awaiting each time? [duplicate]

c#,.net,async-await,task-parallel-library

Yes, you should be able to use something like: public async void SendSeveralRequestsAsync(MyClass myClass) { var client = SomeExternalServiceClient(); var tasks = myClass .Select(item => new ExternalServiceRequest { Value = item.Value }) .Select(request => client.SendAsync(request)); await Task.WhenAll(tasks); } Or perhaps even better - as I don't like returning void from...

Many nested AggregateExceptions

c#,async-await,entity-framework-7,aggregateexception

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...

How to run 2 StreamWriters in parallel [closed]

c#,multithreading,async-await,task-parallel-library,streamwriter

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...

Is it good to call Thread.Sleep during polling Google Big Query results in ASP.NET? Alternatives?

c#,asp.net,asp.net-mvc,async-await,google-bigquery

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...

What is the best approach to make Data Receive / Data Listener keeps alive?

c#,async-await,tcp

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...

Would async/await provide benefit over Task for intertwined statements?

c#,.net,asynchronous,async-await,task-parallel-library

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...

ReaderWriterLockSlim how to wait to enter lock?

c#,multithreading,asynchronous,async-await

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...