FAQ Database Discussion Community


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

c#,asynchronous,async-await
I'm trying to decide how to wait on all async tasks to complete. Here is the code I currently have [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); return this.Json(new {redirect = true, href...

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

c#,async-await,tcp
I have task to create a client application for data communication via TCP and I have no experience in TCP data communication programming. I use C# and VS2013. In the company I work at there is a black-boxed server application. I only know its ip, port and its behaviors on...

Async task raises NotImplementedException

c#,windows-phone-8.1,async-await,.net-4.5
I continue to struggle with Windows Phone programming. :) When invoking the method: public static async Task<string> ConvertToBase64(this BitmapImage bitmapImage) { RandomAccessStreamReference rasr = RandomAccessStreamReference.CreateFromUri(bitmapImage.UriSource); var streamWithContent = await rasr.OpenReadAsync(); byte[] buffer = new byte[streamWithContent.Size]; var result = await streamWithContent.ReadAsync(buffer.AsBuffer(), (uint)streamWithContent.Size, InputStreamOptions.None); using (MemoryStream ms = new...

Run async method regularly with specified interval

c#,asp.net,.net,multithreading,async-await
I need to publish some data to the service from the C# web application. The data itself is collected when user uses the application (a kind of usage statistics). I don't want to send data to the service during each user's request, I would rather collect the data in the...

Async operations and UI update

c#,wpf,multithreading,async-await,caliburn.micro
In a wpf application made of caliburn micro and telerik controls I've different screens that load data from a remote service then show data in a gridview /fills comboboxes. I'm using a sync/await operators to make the load retrieval operations but I'm almost certain it has some bottleneck. Doing await...

Task await fails

c#,asynchronous,async-await,signalr,task
I am starting a HubConnection. First I get a new Instance of HubConnection, afterwards I create a new IHubProxy with Name = "fileHub" so far so good. My problem is located at (or in) the awaitable Function ContinueWith, I try to start the Connection, and write to the console wheater...

await Task vs await Task.Run(voidMethod)

c#,asynchronous,async-await
I'm confused why the output of these 2 programs differs: private async void button1_Click(object sender, EventArgs e) { for (int i = 0; i < 33; i++) { await LongProcess(); } } private async Task LongProcess() { await Task.Delay(1000); progressBar1.Value += 3; } and private async void button1_Click(object sender, EventArgs...

C# Async method call all the way to Main

c#,async-await
Can someone clarify this example, which of course, is not working: class Program { static void Main(string[] args)//main cant' be async { int res = test();//I must put await here Console.WriteLine("END"); } public async static Task<int> test() { //why can't I make it just: public int test()?? int a1, a2,...

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

c#,async-await,task-parallel-library,c#-5.0
When I use the Task.WhenAll() function and an exception is thrown in a Task a new AggregateException is thrown, I can catch it to see all the exceptions that occurred in the Tasks. However, when I use Task.WhenAny() no exception is thrown. Instead, I have to check the Task.Exception property...

Not getting the hang of TASKs and WAIT in C#

c#,asynchronous,async-await,task
I have a stack of calls to a web api that need to be called asynchronously. I have never used the aysnc. I have created a simple test console program, along the lines of : class Program { static void Main(string[] args) { ClassOne xx = new ClassOne(); var v1...

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

c#,async-await
I have implemented a method to handle exceptions around a async block like below: public async Task<ServiceResponse<T>> RetryTest<T>(Func<Task<ServiceResponse<T>>> method) { try { return await method.Invoke(); } catch (Exception exception) { return FormatExceptionResponse<T>(exception); } } And use it to wrap async code like: public async Task<ServiceResponse<DataJob>> Insert(DataJob entity) { return await...

.Net Task class - please explain

c#,.net,asynchronous,async-await,task
Can someone please explain why the public async Task DoStuff() method below can still work without returning anything? It doesn't say void, so I assumed the return type would have to be Task. When I remove the async and await keywords from the DoStuff() method, the compiler gives me a...

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

c#,async-await,task-parallel-library
Sorry for bad title. I am currently learning TPL and reading this blog article which states The ability to invoke a synchronous method asynchronously does nothing for scalability, because you’re typically still consuming the same amount of resources you would have if you’d invoked it synchronously (in fact, you’re using...

async await for a HttpClient.PostAsync call

c#,asynchronous,async-await,dotnet-httpclient
I'm trying to wrap a call to PostAsync so I don't have to recode the call sequence all over my code base. The issue I'm having is the HttpResponseMessage I assigned from the call is not the same as the one the consumer of my method calls. Here is the...

Using HttpClient.GetAsync to call Web API seems to hang

c#,asp.net,asp.net-web-api,async-await,task-parallel-library
I'm working on a proof of concept prototype. I have Asp.Net C# web form (Visual Studio 2013, .Net 4.5) page. On a button click I do something like this: List<Blog> blogs = null; protected void btnLoadData_Click(object sender, EventArgs e) { //...; switch (int.Parse(rblDataSource.SelectedValue)) { //...; case 4: RunAsyncBlogs().Wait(); break; default:...

ObjectDisposedException when trying to access Thread.CurrentPrincipal with async method

c#,multithreading,asynchronous,async-await
I'm fairly new to the new async/await stuff. However, I have the following classes: public abstract class PluginBase { //Using EF to store log info to database private EFContext _context = new EFContext(); private int Id = 1; protected void LogEvent(string event, string details) { _context.LogEvents.Add(new LogItem(){ PluginId = this.Id,...

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

c#,asp.net-mvc,async-await
I have an MVC controller method that does a number of things, but the last thing it does is this: public void PerformCheckout(int salesAddressId) { try { ... ... // We just made a sale. Send emails to all market owners. SendSalesEmailsAsync(master); } catch (System.Exception exception) { // Log the...

Best way to execute asynchronous task on main thread

c#,.net,wpf,asynchronous,async-await
I would like to know what is the best asynchronous way to execute a task on the main thread of a .NET application (in a ViewModel to be precise). Is Dispatcher.BeginInvoke still valid nowadays or does it exist a better way to do that ?

C# Cannot replace void with async Task

c#,async-await
I have the following class derived from entity framework class as follows. internal class MyInitializer : CreateDatabaseIfNotExists<ConfigurationDbContext> { protected override async void Seed(ConfigurationDbContext context) { await DbHelper.AddSampleDataAsync(context); base.Seed(context); } } I get the following compiler error when I change "void" to "async Task". return type must be 'void' to match...

SaveChangesAsync not updating value in database table

c#,asp.net-mvc,entity-framework,async-await
This is my Table:Statistics Id,Depth,RefreshCounter Sample Records: Id Depth RefreshCounter 1 1 1 2 1 0 3 1 0 4 1 0 Now what i need to do is whenever i am refreshing the page i need to increment this refreshcounter value by 1 in Database table with Depth 1....

Sequential version of Task.WhenAll

c#,async-await
Is there a none blocking Task.WaitAll similar to Task.WhenAll but not parallel? I wrote this, but maybe its built in? public async Task<IEnumerable<T>> AwaitAllAsync<T>(IEnumerable<Task<T>> tasks) { List<T> result = new List<T>(); foreach(var task in tasks) { result.Add(await task); } return result; } Edit: for those who vote for close, I...

Testing an asynchronous WCF service using MSTest

c#,.net,wcf,async-await,mstest
I've implemented a WCF service using the async\await method in C#. The service operation contract is as follows: [OperationContract] Task<ResponseMessage<ProcessMultipleTransactionsResponse>> ProcessMultipleTransactionsAsync(RequestMessage<ProcessMultipleTransactionsRequest> msgIn); The method signature for the implementation is: public async Task<ResponseMessage<ProcessMultipleTransactionsResponse>> ProcessMultipleTransactionsAsync(RequestMessage<ProcessMultipleTransactionsRequest> msgIn) I'm...

ASP.NET call hangs on async await

asp.net,async-await,iis-express
My calls to a Google API from an API Controller in IIS express hang indefinitely when called sequentially using async await. var id = CreateDocument("My Title").Result; async Task<string> CreateDocument(string title) { var file = new GData.File { Title = title }; // Stepping over this line in the debugger never...

Wait IAsyncResult function until complete

c#,.net,asynchronous,async-await,iasyncresult
I need to create mechanism which waits IAsycnResult method till complete. How can i achieve this ? IAsyncResult result = _contactGroupServices.BeginDeleteContact( contactToRemove.Uri, ar => { try { _contactGroupServices.EndDeleteContact(ar); } catch (RealTimeException rtex) { Console.WriteLine(rtex); } }, null ); ...

Running c# async method in f# workflow

f#,async-await,c#-to-f#
I am trying to get the below code to work in a F# async workflow, but I am getting the error "Unexpected symbol '}' in expression". I am fairly new to both F# and async in general. What am I missing here. let someFunction (req : HttpRequestMesssage) a b =...

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
I am using web api 2, and entity framework 6. I have created an async web api, which updates all the records at once. I am also using Autofac for dependency injection. My service interface is as follows : Task<Approval> TakeAction(int id, bool isApprove) void TakeAction(bool isApprove) These are my...

ConfigureAwait for IObservable

c#,asynchronous,async-await,system.reactive
I'm experiencing a deadlock when I use blocking code with Task.Wait(), waiting an async method that inside awaits an Rx LINQ query. This is an example: public void BlockingCode() { this.ExecuteAsync().Wait(); } public async Task ExecuteAsync() { await this.service.GetFooAsync().ConfigureAwait(false); //This is the RX query that doesn't support ConfigureAwaitawait await this.service.Receiver...

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

c#,.net,asynchronous,async-await,task-parallel-library
I have a method (called via an AJAX request) that runs at the end of a sequence. In this method I save to the database, send emails, look up a bunch of info in other APIs/databases, correlate things together, etc.. I just refactored the original method into a second revision...

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
This question already has an answer here: Using async/await for multiple tasks 2 answers I have the following piece of code (changed the names of my classes/objects for brevity). It essentially is hitting an external API that allows only a single operation, but my service code will expose it...

Async await usage for MongoDB repository

c#,mongodb,asynchronous,parallel-processing,async-await
I have a MongoDB repository class as you see below: public class MongoDbRepository<TEntity> : IRepository<TEntity> where TEntity : EntityBase { private IMongoClient client; private IMongoDatabase database; private IMongoCollection<TEntity> collection; public MongoDbRepository() { client = new MongoClient(); database = client.GetDatabase("Test"); collection = database.GetCollection<TEntity>(typeof(TEntity).Name); } public async Task Insert(TEntity entity) { if...

How to run 2 StreamWriters in parallel [closed]

c#,multithreading,async-await,task-parallel-library,streamwriter
Recently I was working on a project to write a csv file and an XML file at the same time. They contain the same metadata information, how to open two StreamWriters in C# at the same time?

Using asyn await in foreach loop

c#,async-await,task-parallel-library
Is it incorrect to use asyc await in a foreach loop? I get a WebException, The request was canceled. The following is just a outline of the code I’m working on. Please let me know if this is not clear. using (var client = new HttpClient()) { client.BaseAddress = new...

HttpClient returning special characters but nothing readable

c#,wpf,async-await,httpclient
I am trying to download a webpage using async and await and HttpClient, but am getting only a string full of special characters... Code is like.. static async void DownloadPageAsync(string url) { HttpClient client = new HttpClient(); client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml"); client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate"); client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64;...

Combine Results from Async Method and Return Synchronously

c#,azure,asynchronous,async-await
I've read many posts where people have faced similar issues but they seem to make assumptions that don't apply or their code simply does not work for me. I need to combine results from asynchronous methods. The ONLY thing async that I want is the combining of the results. Since...

How to setup multiple async methods into a queue?

c#,.net,queue,async-await,.net-4.5
I just picked up async/await, and I wrote a series of async methods that each perform a database SQL task and tied each one to a different button. The GUI doesn't get locked when you click a button, so I figure that's awesome. However, if you click each one the...

ReaderWriterLockSlim how to wait to enter lock?

c#,multithreading,asynchronous,async-await
I am trying to use ReaderWriterLockSlim to lock some database work in an async method like this: readerWriterLock.EnterWriteLock(); using (var db = new MyContextDB()) { // look something up and alter it } readerWriterLock.ExitWriteLock(); This throws an exception as multiple threads try to enter writelock at the same time. Right...

How to await a ParallelQuery with LINQ?

linq,asynchronous,async-await,parallel-extensions
I have an async method, that should look up database entries. It filters by name, thus is a candiate for parallel execution. However, I can not find a simple way to support both parallel execution and asynchronous tasks. Here's what I have: private async Task<List<Item>> GetMatchingItems(string name) { using (var...

Merge asyc method into one task

c#,.net,asynchronous,async-await
Not sure if this is possible or if it already does something simpler with chained tasks internally, could not work it out from the info I read. public async Task<ClaimsIdentity> CreateIdentity(string userid ) { Guid gid = Guid.Parse(userid); Avatar avatar = await _dbContext.Users.Where(d => d.Id == gid).FirstOrDefaultAsync(); return await CreateIdentity(avatar);...

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

c#,xamarin,async-await
I am working on a xamarin project with a partner. Xamarin allows the use of C# in coding for iOS or Android. Here is an example of some code a coworker wrote that I feel could be done in a substantially better way: alert = new AlertDialog.Builder (Act); alert.SetOnDismissListener(new OnDismissListener(()...

How to catch an OperationCanceledException when using ContinueWith

c#,asynchronous,.net-4.0,async-await
I have some code I'm downgrading from .NET 4.5's lovely async and await keywords to .NET 4.0. I'm using ContinueWith to create a continuation similar to the way await works. Basically, my old code was: var tokenSource = newCancellationTokenSource(); var myTask = Task.Run(() => { return MyStaticClass.DoStuff(tokenSource.Token); }, tokenSource.Token); try...

Mock async Get method with MOQ

c#,.net,async-await,moq
How do I get rid of this error message: Error 5 Cannot implicitly convert type 'System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<TGB.Business.DTO.SchoolyearDTO>>' to 'System.Collections.Generic.IEnumerable<TGB.Business.DTO.SchoolyearDTO>'. An explicit conversion exists (are you missing a cast?) I thought my Task.FromResult would fix that but no... mockService.Setup<IEnumerable<SchoolyearDTO>>(c => c.GetSchoolyears()).Returns( Task.FromResult(Enumerable.Empty<SchoolyearDTO>()));...

Potential cause for ExecuteReaderAsync to lose context

c#,async-await,task-parallel-library
I've done a little abstraction on top of our data access layer, to abstract away whether we're using ole, mssql or others. Oddly enough the following case works fine in the unit test with the exact same parameters but fails when called from our mvc application. The code in question...

Is it incorrect to call async methods synchronously in unit tests?

c#,unit-testing,asynchronous,async-await,typemock-isolator
I'm new to the async/await world and I'm trying to figure out the benefits of writing asynchronous unit tests for async methods. That is, must a unit test for an async method call that async method asynchronously? If it calls the async method synchronously using Task.Run(), what is lost? In...

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

c#,.net,asynchronous,async-await
I have a question about asynchronous programming in C#. I want to know why a function that has a return type of Task has to return a string. So even through I returned a string, it gets wrapped into a Task again - why is that? Problem is that I...

Asynchronous MVVM commands

wpf,asynchronous,mvvm,async-await,task-parallel-library
I have been following the rather excellent series of articles by Stephen Cleary in the MSDN magazine (Patterns for Asynchronous MVVM Applications) and have been using his IAsyncCommand pattern in a "hello world" style application. However, one area that he does not address is when one needs to pass in...

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

c#,.net,async-await,task-parallel-library
I'm trying to use Task.WaitAll on a list of tasks. The thing is the tasks are an async lambda which breaks Tasks.WaitAll as it never waits. Here is an example code block: List<Task> tasks = new List<Task>(); tasks.Add(Task.Factory.StartNew(async () => { using (dbContext = new DatabaseContext()) { var records =...

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

c#,.net,wpf,async-await,.net-4.5
I have been trying to setup a very basic method in my view models for temporarily freezing the UI thread while still pumping dispatcher messages, I have read this method will only work for simple cases and is not thread safe as 'waiting' for a task while already 'waiting' for...

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
I have WP 8.1 app that using web service a lot, and I want to keep it as much responsive as possible. From iOS dev expierense - there is one strict rule: "Do not do in UI thread any complex calculations! Doesnt matter how you will reach this: with blocks...

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

c#,asynchronous,exception-handling,async-await,task-parallel-library
I'm unsure about two possibilities to react to an event in my code. Mostly I'm concerned about which one needs less resources. I have a method with an observer registered to an eventproducer. If the eventproducer returns something, the method exits and the caller of the method starts the method...

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 am using ASP.NET MVC 5 which gets data from Google Big Query. Due to the way Google Big Query is designed, I need to poll for results if job is not finished. Here is my code, var qr = new QueryRequest { Query = string.Format(myQuery, param1, param2) };// all...

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

c#,.net,multithreading,asynchronous,async-await
I'm trying to understand async/await and have read a number of articles but am still confused about the synchronous/asynchronous nature. I have the following test console app: static void Main(string[] args) { var test = FooAsync(); Console.WriteLine("After FooAsync"); for (int i = 0; i < 100; i++) Console.WriteLine("After that"); Console.ReadKey();...

Why async code is run on worker thread in C#

c#,multithreading,asynchronous,async-await
I am playing with the async/await in the C# and while I think that I understand most of the concepts, I can not explain why the code line "var rxres = await ..." first time runs on my UDP thread, and after further receptions of the packets runs on the...

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

c#,asp.net,.net,async-await,task-parallel-library
I'm getting my feet wet with .NET 4.5's async/await construct. I'm working on a RESTful Web API solution. I'm trying to figure out what to do with CPU-bound operation - 1) call it synchronously from the current thread, or 2) use Task.Run()? Let's use the example from this page: async...

Run async method in overridden void

c#,asp.net,asp.net-mvc,asp.net-mvc-5,async-await
I'm currently building an ASP.NET MVC application. I'm trying to add items to the ViewBag property for all pages in my site. To achieve this, I've created a base controller that all my site controllers inherit from. To add to the ViewBag, I've overridden the OnActionExecuting method: protected override void...

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

c#,async-await
I'm trying out async/await code in a new C# 4.5 web application on VS 2013. It's a web application running on my developer machine under IISExpress. I'm setting a breakpoint in the async method and can see that the method completes as expected. But then the next line of code...

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

c#,asp.net,unit-testing,asp.net-web-api,async-await
I'm currently seeing a problem whereby my await method is just hanging, and causing the response to just hang, not doing anything until I kill the request. This is evident in both Chrome debug tools and Fiddler. I have the following API action defined: [Route("state/{stateCode}")] [LogApiCallFilter] public async Task<IList<MapPlaceDTO>> GetWithinState(string...

Guarantee TransformBlock output sequence

c#,multithreading,async-await,task-parallel-library,tpl-dataflow
From the TPL documentation As with ActionBlock<TInput>, TransformBlock<TInput,TOutput> defaults to processing one message at a time, maintaining strict FIFO ordering. However, in a multi-threaded scenario, i.e. if multiple threads are "simultaneously" doing SendAsync and then "awaiting" for a result by calling ReceiveAsync, how do we guarantee that the thread that...

await/async odd behaviour

c#,.net,asynchronous,async-await,task-parallel-library
I have a simple Console Application using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication2 { public class Program { static void Main(string[] args) { MockAPI api = new MockAPI(); Task t = api.GetVersion(); var placeBreakPoint = "breakpoint"; } } public class MockAPI { public async Task<string>...

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

c#,async-await,dotnet-httpclient,connection-timeout
We are using an HttpClient to post json to a restful web service. In one instance, we are running into something that has us baffled. Using tools like postman, fiddler etc, we can post to an endpoint and see that it is working. When we do the same with HttpClient.PostAsJsonAsync,...

Async/await with CancellationToken doesn't cancel the operation

c#,async-await,cancellationtokensource
I want to use the CancellationToken to abort a file download. This is what I tried: public async Task retrieveDocument(Document document) { // do some preparation work first before retrieving the document (not shown here) if (cancelToken == null) { cancelToken = new CancellationTokenSource(); try { Document documentResult = await...

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

c#,.net,windows-phone-8.1,async-await
i am trying to receive a response from a HttpClient in Windows Phone 8.1 but it hangs on the method: httpClient.SendRequestAsync(requestMessage); The code looks like this: // Create a client var httpClient = new HttpClient(); // Add a new Request Message var requestMessage = new HttpRequestMessage(HttpMethod.Post, new Uri(serviceUri)); // Add...

Async thread body loop, It just works, but how?

c#,.net,multithreading,asynchronous,async-await
I have just tested something that I was sure would fail miserably, but to my surprise, it worked flawlessly, and proves to myself that I am still quite mystified by how async-await works. I created a thread, passing an async void delegate as the thread's body. Here's an oversimplification of...

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

c#,.net,async-await,task-parallel-library
Code sample: using System; using System.Threading.Tasks; public class Program { public static void Main() { Console.WriteLine("Start"); Foo f = new Foo(); f.FooAsync(); } public class Foo { public async void FooAsync() { try { await Task.Run(() => { Console.WriteLine("Throwing"); throw new Exception(); }); } catch (Exception) { Console.WriteLine("Caught"); } }...

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

c#,asynchronous,async-await,semaphore
The situation I am uncertain of concerns the usage of a "threadsafe" PipeStream where multiple threads can add messages to be written. If there is no queue of messages to be written, the current thread will begin writing to the reading party. If there is a queue, and the queue...

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

c#,com,async-await,activex,rcw
I recently came across a strange bug in my async code. I was calling a blocking method on a COM control, which appeared to allow my async continuations to run while it was blocking. Consider example code (illustrative purposes only) public async void Main() { //assume some single threaded dispatcher....

Async/Await in foreach with HTTPClient

c#,asynchronous,async-await
I have a webservice that loads up some plugins (dlls) and calls their Process method. One of the plugins takes a list of members and ensures that they are all included in a MailChimp list. Here is the code that adds the users to the MailChimp group. private async Task...

Correct way to convert method to async in C#?

c#,asynchronous,async-await
I'm attempting to convert the following method (simplified example) to be asynchronous, as the cacheMissResolver call may be expensive in terms of time (database lookup, network call): // Synchronous version public class ThingCache { private static readonly object _lockObj; // ... other stuff public Thing Get(string key, Func<Thing> cacheMissResolver) {...

Write async method correctly

c#,asynchronous,methods,async-await,task-parallel-library
I've used async methods for a long time, but I don't know the right way to write my own async method. As I get it, first root(I mean most deep) async method begins from sync method wrapped in a Task? Am I right? What is the right pattern to write...

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

c#,asynchronous,async-await,task-parallel-library
This question already has an answer here: How does Task<int> become a int? 1 answer I've got code very similar to this (I've simplified the code a bit to demonstrate the essence of the behavior I'm trying to figure out). public async System.Threading.Tasks.Task<bool> IsNumberOdd(int numToTest) { if (numToTest %...

Implicit awaiting?

c#,asynchronous,async-await
I have a method Create : public async Task<MyObject> Create(string str1, string str2) { // Check to see if a MyObject can be created in the database. if (!await CanCreate(str1, str2)) { return null; } // Create the object. var myObj = new MyObject { Created = DateTime.Now.Date, First =...

How to ask the GUI thread to create objects?

c#,multithreading,winforms,async-await
I've got the following program flow in my Windows Forms application (WPF is not a viable option unfortunately): The GUI Thread creates a splash screen and a pretty empty main window, both inheriting Form. The splash screen is shown and given to Application.Run(). The splash screen will send an event...

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

c#,asp.net-mvc,async-await,task-parallel-library,smtpclient
I am getting error "An asynchronous module or handler completed while an asynchronous operation was still pending" while using SendMailAsync. My code : public static async Task SendEmail(MessageContent messageContent, string emailBody) { SmtpClient smtpClientNoSend = new SmtpClient(); await smtpClientNoSend.SendMailAsync(mailMessage); } Call From Controller : public async System.Threading.Tasks.Task<ActionResult> Register() { await...

Using the result of an async method

c#,asynchronous,async-await
I have a simple async method with the signature: public async Task<bool> AllowAccessAsync(string authenticatedUserToken) When calling this method, I appear to have two options when assigning its result to a local variable: bool response = null; // option 1 await this.transportService.AllowAccessAsync(authenticatedUserToken).ContinueWith(task => response = task.Result); // option 2 response =...

Proper way to handle a group of asynchronous calls in parallel

c#,parallel-processing,async-await,task
I have a console app that calls a web api and gets a list of services. It then loops through and makes calls to each service. I have the following: static int Main(string[] args) { ... Task.WaitAll(Process()); } private static async Task BeginProcess() { using(HttpClientHandler handler = new HttpClientHandler()) {...

ASP.NET and async - how it works?

asp.net,asp.net-mvc,async-await,task-parallel-library
I know that is a common question, but I've read a kiloton of articles and feel confused. And now I think that it would be better not to read them at all )). So, how ASP.NET works (only about threads): http request is served by thread from the thread pool....

Async/Await handling group of HttpResponseMessage

c#,asynchronous,async-await
I previously posted a question about using HTTPClient with async/await. Now I'm trying to figure out how to do this in such a way as to actually make the Post calls execute at the same time while still being able to handle the resulting HttpResponseMessage. This is what I've come...

C# async await simple issue

c#,asynchronous,async-await
I'm just learning about task, and async/await implementation and I'm struggling with a simple code example so I was hoping someone could share some lights as to what is going on. here's the code: public async Task<string> DoStuff() { Console.WriteLine("Long running op started"); var myString = await Task<string>.Run(() => {...

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
In the below code, 42 is printed to the Console before "Almost done" is. Since 42 has already been returned, how is the control still in AsyncCheck? I understand that if the task has not completed at 'await', it will return the control but here I have an explicit return...

Implication of calling result on awaited task

c#,.net,asynchronous,async-await
Given we have some kind of rudimentary async CQRS setup like the below: public interface IRequest<TReturn> { } public interface IRequestHandler<TRequest, TReturn> where TRequest : IRequest<TReturn> { Task<TReturn> RequestAsync<TRequest>(TRequest request); } public class GetThings : IRequest<string[]> { } public class GetThingsHandler : IRequestHandler<GetThings, string[]> { public async Task<string[]> RequestAsync<TRequest>(TRequest request)...

How async works understood correctly?

async-await
List<Results> stuff = DoSomeStuff(); await Task.run(SomeAsyncAction); return stuff; I have something similar to the above in my program. The task is supposed to update my database with results from an expensive calculation. Does this mean my async method would never execute the return statement until the awaitable has completed even...

WCF WebMethod with a blocking call

c#,wcf,async-await
I am relatively new to the WCF paradigm and have a simple task at hand . I have a webmethod like this . [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/GetUser", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] User GetUserById(User user); I have impled this method in the following manner public GetUserById(User...

Many nested AggregateExceptions

c#,async-await,entity-framework-7,aggregateexception
Working with Entity Framework 7, I made a simple mistake with some linq (used Skip and forgot to include my OrderBy clause). The exception that was thrown by this included a number of nested aggregate exceptions. The code that generates (and catches) the exception is: int[] newIds; try { newIds...

Async void method in Console doesn't want to fire

c#,console,async-await
Why don't I see anything in the console when I run the program below? Screenshot for proof. I see both done-messages when I uncomment both lines (why not only "Foo Done!"?) class Program { static void Main(string[] args) { //var foo = new Foo(); var bar = new Bar(); }...

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

c#,.net,async-await
I have a sync method, now I would like to implement its async version. Fortunately the underlying call already have an async version (dbSet.SaveChangesAsync()), however in my algorithm there is an if branch returning with constant literal 1. I do not know how to implement this part in the async...

Unable to use result of Async DocumentDB operation CreateDocumentAsync

c#,azure,async-await,task-parallel-library,azure-documentdb
I have created a documentDB on Azure and can successfully create and get documents. However, whilst documents are successfully created in the DB, I am not able to use the response from CreateDocumentAsync. The code immediately returns to the calling method on the controller. So the debug line is never...

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

c#,asp.net-mvc,async-await
I'm just learning how to use async and await. Say I have the following method that sends an email: public async void Send() { // Create a network credentials object var credentials = new NetworkCredential(azureUserName, azurePassword); // Create an Web transport for sending the email var transportWeb = new Web(credentials);...

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

c#,asp.net,asp.net-mvc,asynchronous,async-await
I'm starting with Async MVC and I would like to know wich is the main difference between this two implementations of an AsyncController. The first one is using the ViewNameAsync and ViewNameCompleted implementation: public class HomeController : AsyncController { // ... Manager declaration ... public void IndexAsync() { AsyncManager.OutstandingOperations.Increment(); Manager.ExpensiveOperationCompleted...

Can requests be handled on a separate thread?

asp.net-mvc,multithreading,async-await,httprequest
In my ASP.NET MVC web application I'm consuming a web service that sometimes might take long to respond. In this case the user might want to cancel the request and be able to make other requests. But as the server is still busy processing the previous request, the user has...

Function Running Sync When VS Says it should be running async

c#,.net,async-await
Why Does B Run Sync? Vs Says ."Because this call is not awaited, execution of the current method continues before the call is completed." ; A) Task.Factory.StartNew(() => Funcation(1, 1)); //Runs Async B) Funcation(1, 1); // Says it runs async in vs, but really runs sync. C) var handleOne =...

Task.StartNew() works differently on STA mode?

c#,wpf,multithreading,async-await,task-parallel-library
I am quite new to this whole threading thing, so hopefully someone can enlighten me. I have a WPF UI from which I start a DLL on the click of a button. When the button is clicked, it runs the dll asynchronously so that the user can still "navigate" the...

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
I've been attempting to implement a Stream that supports ReadAsync and WriteAsync, and given the spareseness of the documentation, I'm struggling to understand how to do so properly. Specifically, with respect to the stream's cursor position. A similar question was asked here and here regarding the old BeginRead function. The...

Losing HttpContext with async await in ASP.NET Identity GetRolesAsync

c#,asp.net-web-api,async-await,asp.net-identity
This is more of an async/await question than ASP.NET Identity. I am using Asp.Net Identity, and have a custom UserStore, with a customized GetRolesAsync method. The UserManager is called from a WebApi controller. public class MyWebApiController { private MyUserManager manager = new MyUserManager(new MyUserStore()); [HttpGet] public async Task<bool> MyWebApiMethod(int x)...

Correct use of async and await

c#,async-await
I'm just starting to deal with Asynchronous programming in c#, and I started reading about async methods and await. In this block of code below, the WPF application takes an input from the user, saves it to a file in the Bin directory, and reads it back to the textbox....

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

c#,unit-testing,async-await,task
I am trying to test a method whose signature is of the form public async Task<List<int>> MethodToBeTested() I have written a unit test as follows [TestMethod] public async Task MethodToBeTestedSuccess() { Task<List<int>> results = await MethodToBeTested() ...... } If the method's return type had been a generic List of integers...

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

c#,entity-framework,asp.net-mvc-5,async-await
Why is this Task not returning anything to the view? If I convert it to synchronous then it works, or if I step through the async task in visual studio, it works also. public async Task<ActionResult> Load() { var housing = _db.Housing.ToListAsync(); var school = _db.Schools.ToListAsync(); var projects = _db.Projects.ToListAsync();...

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

c#,.net,asynchronous,async-await
I have some users. Each user has a List of Products. Each user is stored in blob storage with their products so I want to retrieve them in parallel which I can do fine. The problem is that when each set of products are returned I don't know which user...

Writing/Reading To/From File Windows 8.1 AppStore App

c#,async-await,windows-applications
I have a Windows 8.1 App from which I want to write to and read from an XML file that is put in the "Assets" folder in the Application package. I call the following method from the page constructor after the this.InitializeComponent(); line: private async void ReadXML() { var uri...

Implementing SendBatchAsync for Microsoft Azure Service Bus Brokered Messages

c#,azure,async-await,azureservicebus,brokeredmessage
My requirement is that I have to send a list of brokered messages to the azure service bus asynchronously. However I am not able to implement the SendBatchAsync method properly. Let me explain in detail. Here is my code: public async Task SendBatchEnrollmentMessages() { while(somevalue) { //logic to fetch data...

How to handle async & await with default override's

c#,android,asynchronous,xamarin,async-await
In a Xamarin project, Android - I am new to android development. While working on a activity, in the OnCreate method am setting a custom Adapter for a ListView. protected async override void OnCreate (Bundle bundle) { base.OnCreate (bundle); SetContentView(Resource.Layout.Main); var listAdapter = new CustomListAdapter(this); //................................................. listView = (ListView) FindViewById(Resource.Id.list);...

Triggering events from async/await functions in the right order

c#,events,design-patterns,asynchronous,async-await
I have problems ensuring the order of events in my asynchronous task. The class from which other async tasks inherit has the following functions and takes the EventHandlers (ExecutionProgress, ExecutionStarted, ExecutionCompleted) in the constructor arguments: public abstract Task Operation(IProgress<EventArgs> progress); public virtual void Execute() { ExecuteAsync() } private void ReportProgress(EventArgs...