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

c#,asynchronous,task-parallel-library,async-await
I'm new to asynchronous programming, and I have been working on a small example to demonstrate how to program with tasks. I was wondering about your opinions on the sample. Am I blocking anywhere? Am I doing anything wrong? Can it be made better somehow? Here is the code of...

task-parallel-library,tpl-dataflow
Through TPL dataflow one can assign MaxDegreeOfParallelism for the block to run in parallel, another way is to 'load balance' the load by connecting the source to multiple target by limit the BoundedCapacity of each target block. Question, what is the difference with two approaches, why do I even bother...

c#,task-parallel-library
I have an external library that returns Task<T>. My library wraps this call and does a translation and returns Task<T2>. How can I create my Task that will run on completion of Task without using a .Wait() or .Result? Feels like a .ContinueWith() should do it, but I'm struggling with...

c#,task-parallel-library,async-await,.net-4.5,c#-5.0
I am learning TPL (async/await) from a tutorial and I tried to test it out myself using a console application. Please don't be offended by my ignorance. I am sure I am doing wrong somewhere- I wrote the following code: static void Main(string[] args_) { Task<int> task = ProcessNumber(25); Console.WriteLine(string.Format("{0}:...

c#,asynchronous,lambda,async-await,task-parallel-library
I have the following method that returns before it completes (method cut down for brevity): private void ProcessAllItems(List<Item> items) { items.ForEach(async item => { var response = await Processor.IOBoundTaskAsync(item); // Some further processing on the response object. }); } The Processor.IOBoundTaskAsync method returns a Task<SomeResponseObject>, so not a void. So,...

c#,.net,asynchronous,task-parallel-library,async-await
I have a button that - when the user clicks it - sends an email. I'd love for this to just return immediately and send the email in the background without holding up the UI as the email is processed. I've searched around for async/await/etc and I've found so many...

c#,.net,asynchronous,task-parallel-library,async-await
This question already has an answer here: Using async/await for multiple tasks 2 answers I have a situation where I want to fire off a user-defined number of tasks asynchronously and wait for all of them to complete. Simplified, here's what I'm dealing with: [TestMethod] public async Task Start()...

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

c#,task-parallel-library
wonder if you can help. I have a listview displaying a list of Customer EG (Customer1,Customer2,Customer3 etc..) Now each customer can have 1000s of orders to process so The problem I have is that I would like to wait for processcustomer to finish before starting with new one,and I dont...

c#,.net,c#-4.0,task-parallel-library
I'm trying to manage a list of tasks for a Windows Service so when I shut down the Service, I can use the Task.WaitAll() method to stop the Service from shutting down until all of the remaining tasks complete. For example, I have a Run() method that executes until a...

c#,task-parallel-library,task
I'm tying stop thread by nothing works. I was trying on 100 ways. What is wrong ? It is irritating (I have to write some text here because stackoverflow.com don't allow me to send this post)(I have to write some text here because stackoverflow.com don't allow me to send this...

.net,task-parallel-library,tpl-dataflow
I know the following works: var forwarder = new BufferBlock<SomeType>(); forwarder.LinkTo(target1, item => matchesTarget1(item)); forwarder.LinkTo(target2, item => matchesTarget2(item)); forwarder.LinkTo(DataflowBlock.NullTarget<SomeType>()); The problem is I will be linking and unlinking items continuously at runtime. Will dataflow choose from most specific to least specific or will it go in the order things were...

c#,.net,task-parallel-library,async-await,deadlock
I seem to be experiencing a deadlock with the following code, but I do not understand why. From a certain point in code I call this method. public async Task<SearchResult> Search(SearchData searchData) { var tasks = new List<Task<FolderResult>>(); using (var serviceClient = new Service.ServiceClient()) { foreach (var result in MethodThatCallsWebservice(serviceClient,...

c#,.net,task-parallel-library,async-await,dotnet-httpclient
I'm needing to create a list of tasks to execute a routine that takes one parameter and then wait for those tasks to complete before continuing with the rest of the program code. Here is an example: List<Task> tasks = new List<Task>(); foreach (string URL in LIST_URL_COLLECTION) { tasks[i] =...

c#,.net,task-parallel-library,async-await,io-completion-ports
Based on numerous books and blogs including this excellent one here, it is clear that when one writes a dll library exposing helper async methods i.e. the wrapper methods, it is generally considered a best practice to internally complete the I/O task of actual async methods on a threadpool thread...

c#,.net,task-parallel-library,throttling,tpl-dataflow
I want to limit the number of items posted in a Dataflow pipeline. The number of items depends of the production environment. These objects consume a large amount of memory (images) so I would like to post them when the last block of the pipeline has done its job. I...

c#,multithreading,task-parallel-library,volatile,memory-model
Suppose I have a member variable in a class (with atomic read/write data type): bool m_Done = false; And later I create a task to set it to true: Task.Run(() => m_Done = true); I don't care when exactly m_Done will be set to true. My question is do I...

c#,multithreading,asynchronous,task-parallel-library,reentrancy
I am going to use this method in a Load Test which means thousands of calls may happen very quickly from different threads. I am wondering if I have to consider what would happen on subsequent call, where a new WebClient is created but before the prior await is complete?...

c#,task-parallel-library
I am currently on a project about document generation. Given 100.000 customers I need to create a folder for customer and a file inside it. Is it quicker to create all the folders in advance or create file and folders if not exists as I go along in the loop....

c#,linq,parallel-processing,task-parallel-library
I am looking for an example on how to use Parallel.For in C# with a reference type. I have been through the MSDN documentation, and all that I can find are examples that use a value type for thread local storage. The code that I'm trying is as follows: public...

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

c#,concurrency,task-parallel-library,httprequest,task
I'm trying to load test an API. I'm executing a tasks at the same time, each executing an HTTP request. I use Task.WhenAll(mytasks) for waiting for all tasks to be finished. The requests look as follows: using (var response = await client.SendAsync(request).ConfigureAwait(false)) { using (var jsonResponse = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) {...

c#,.net,task-parallel-library,cancellationtokensource,cancellation-token
I don't see any specific mention either on MSDN or here about how to accomplish this. The use case is somewhat obscure, but still valid I suspect. var cancel = new CancellationTokenSource(); var task = Task.Factory.StartNew(() => { Task.Delay(1000, cancel.Token).Wait(); }, cancel.Token); cancel.CancelAfter(100); task.Wait(); The above code will attempt to...

c#,asynchronous,io,task-parallel-library,async-await
Since I have to do a lot of file I/O operations in my application, I decided to implement them asynchronously. Looking into the MSDN, there are no asynchronous counterparts for File.Create, File.Delete and File.Move. As I learned, the reason is the nonexistence of an asynchronous Win32 implementation for file delete,...

c#,.net,task-parallel-library,etw
I am interested in listening to ETW (event tracing for Windows) TPL events, in particular I'd like to know when a Task starts and when it stops. Here's a sample program I've used for testing: using System; using System.Collections.Generic; using System.Diagnostics.Tracing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace...

c#,.net,task-parallel-library,async-await
Hello i have the following code that creates a task. Then sets it to start. The task is meant to add a response to the ConcurrentBag list. But the await does not seem to be waiting for all the tasks to complete. But they are being marked as completed. There...

c#,task-parallel-library,web-api,asp.net-web-api2
I've been seeing some conflicting information on the subject, and I would like to achieve some clarity here. Originally, you would have Web Api actions such as: Model Action(); HttpResponseMessage Action(); Then, with the addition of TPL enhancements to Web Api, you could have Task<Model> Action(); Task<HttpResponseMessage> Action(); And supposedly,...

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

c#,asynchronous,async-await,task-parallel-library
I have a .DLL that I am referencing that was coded asynchronously to call against an API. I have no choice in using this asynchronous API as I was not the one who coded it. Inside this DLL is an asynchronous method called CreateFqrs that returns a type Task'<'List'<'JciFqr>>. I...

c#,asynchronous,task-parallel-library
I have some code that's already asynchronous - just not using the Task system. I would like to make it a lightweight Task, if possible, so that code may leverage it as a Task. So I want to take this: void BeginThing(Action callback); And turn it into this pseudocode: Task...

c#,asynchronous,task-parallel-library,async-await,task
My understanding is that the following is bad practice since it blocks the thread: Task t = Task.Run(() => MyMethod()); t.Wait(); Whilst the following does not block the thread: await MyMethod(); However, to use await, one has to use the async keyword in the method signature, and return a Task...

c#,garbage-collection,task-parallel-library
Example: var task = Task.Factory.StartNew(() => { Thread.Sleep(1000); throw new Exception("fault!"); }); task.GetAwaiter().OnCompleted(() => { if (task.IsFaulted) { Console.WriteLine(task.Exception); } }); The code above waits for task completion using a TaskAwaiter. I've seen code like this in several examples throughout the web, either with OnCompleted or with GetResult. Is it...

c#,.net,multithreading,task-parallel-library,web-api
I have a web api coded in c#. The web api uses functionality which is shared with other in-house components. it depends on single threaded flows and uses thread local storage to store objects, and session information. Please don't say if it's good or bad, that's what I have to...

winforms,task-parallel-library
I want to create an instance of an object from an assembly that implements an interface I define in my Forms app. I would create this object at app startup using Activator.CreateInstance, and keep an application-level reference to it. At certain points during this application I want to call methods...

c#,.net,multithreading,task-parallel-library,task
What values use ContinueWith(Action<Task> continuationAction) for CancellationToken, TaskContinuationOptions and TaskScheduler and where can I find this in the official documentation?

c#,.net,asynchronous,task-parallel-library,async-await
Suppose I have an interface which includes an async method, and I have two different implementations of that interface. One of the two implementations is naturally async, and the other is not. What would be the "most correct" way of implementing the non-async method? public interface ISomething { Task<Foo> DoSomethingAsync();...

c#,error-handling,task-parallel-library,async-await,task
I have a common method that I'm using to handle a specific error that may come back from a number of functions: protected async Task<T> RunMyMethod<T>(Func<T> method) { try { var returnValue = await Task.Run<T>(method); return returnValue; } catch (MyCustomException) { // Force a clean shutdown of the software ShutdownApplication();...

c#,.net,parallel-processing,task-parallel-library,wait
This question already has an answer here: TPL wait for task to complete with a specific return value 2 answers There are three tasks that I wish to run in parallel. I wish to examine the result of the first task that finished and do a check to decide...

c#,asynchronous,progress-bar,task-parallel-library
I am trying to update UI elements from multiple methods using TPL. The elements get updated when the first method is executed but when the child methods nested in the first method are called, I get an InvalidOperationException-The current SynchronizationContext may not be used as a TaskScheduler. I even tried...

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

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

c#,multithreading,thread-safety,task-parallel-library,task
is there any way to increment a value of an int inside a task? or is this a correct syntax in incrementing an int in task? sample code: public int erCount = 9; static void Main(string[] args){ Task.Factory.StartNew(() => { ...do some task if(errorfound) erCount++; }); Task.Wait(); Console.Writeline(erCount.toString()); } I...

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

c#,task-parallel-library
does each thread get its own copy that it can change? Do they all share the same one? Is it thread safe? X var; Parallel.Foreach(ls , it => Op(var, It)); Op does something to var. I assume that if var is a reference (say a List<string>) then there is one...

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

asynchronous,f#,mono,task-parallel-library
I have the following dummy code to test out TPL in F#. (Mono 4.5, xmarin studio, quard core macbook pri) To my surprise, all the processes are done on the same thread. there is not parallelism at all. open System open System.Threading open System.Threading.Tasks let doWork (num:int) (taskId:int) : unit...

c#,asynchronous,task-parallel-library,async-await,task
Depending on whether I'm using async/await based code or TPL based code, I'm getting two different behaviors regarding the clean-up of logical CallContext. I can set and clear logical CallContext exactly as I expect if I use the following async/await code: class Program { static async Task DoSomething() { CallContext.LogicalSetData("hello",...

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

c#,multithreading,linq-to-sql,task-parallel-library,datacontext
I am working on a project that uses a static global DataContext (Which is not recommended but extremely hard to change at this point). I currently need to increase the performance of some parts by parallelizing some functions that are independent. Since DataContext is not thread-safe, I cannot use it...

task-parallel-library,system.reactive,reactive-programming,observable
So the case is this. Suppose somewhere I am filling a Collection. Each time an element is added, an IObservable calls OnNext for its subscribers. Now, there will be a point where the collection will be filled. (I was reading something and I finished reading .. whatever). At that point,...

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

c#,.net,multithreading,exception,task-parallel-library
I got the below code from this article on COLIN Mackay's Blog. Tasks that throw exceptions as this article suggest is that exceptions thrown in the task are not bubbled up Unless one of the of the Wait… methods (excluding WaitAny) is called. well I have 2 similar scenarios that...

c#,multithreading,parallel-processing,task-parallel-library,parallel.foreach
We have used Parallel.Foreach extensively in our code, only challenge we had was how to make it serial while using visual debugging in DEBUG mode, following is what we are doing, please share your view: public static class ParallelOptionsWrapper { // Private instance of ParallelOptions private static readonly ParallelOptions @ParallelOptions;...

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

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

c#,task-parallel-library,parallel.for
I just started to learn about the Parallel.For() in c# and I have a function that doing something and I don't know how to adjust it to be Parallel. Can any anybody show me an example of such similar case? Update: for (int i = 0; i < (samples32array.Length); i...

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

c#,.net,parallel-processing,task-parallel-library,async-await
I have a list of Task. I want to run all tasks in parallel. I am doing it using following code. var tasks = new List<Task>(); foreach (var file in files) { tasks.Add(file.DownloadAsync()); } await Task.WhenAll(tasks); But on every task completion I need to update UI or need to do...

c#,multithreading,task-parallel-library,parallel.foreach
I have a bunch of data rows, and I want to use Parallel.ForEach to compute some value on each row like this... class DataRow { public double A { get; internal set; } public double B { get; internal set; } public double C { get; internal set; } public...

c#,.net,task-parallel-library
Problem: I have filesystem where files appear and i want to upload them over WCF. What i want is to limit maximum number of parallelism to some ThreadMaxConcurrency Idea is to utilize Producer-Consumer pattern in blockingQueue. Producing part is - UploadNewFile,CreateFolder etc... What i am blind of is that consumer...

c#,async-await,task-parallel-library,task,synchronizationcontext
There are lots of guidelines for when to use ConfigureAwait(false), when using await/async in C#. It seems the general recommendation is to use ConfigureAwait(false) in library code, as it rarely depends on the synchronization context. However, assume we are writing some very generic utility code, which takes a function as...

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

c#,multithreading,parallel-processing,task-parallel-library,parallel.foreach
I have read through all the related questions in SO, but a little confused on the best approach for my scenario where multiple web service calls are fired. I have an aggregator service that takes an input, parses and translates it into multiple web requests, makes the web request calls...

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

c#,multithreading,httpwebrequest,task-parallel-library
I am stress testing the server and thus creating the HttpWebRequest inside the factory but when the response time for various number of threads is checked then for 1 thread the response time is high and when number of threads increases then response time decreases. what can be the reason?...

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

c#,.net,multithreading,task-parallel-library,task
Do you see any pitfalls or issues when spawning off two separate tasks for an Oracle db query and Active Directory query and then waiting for both. Below is a very basic stripped down example. Essentially we have an employee object that gets created from pieces of info from AD...

c#,linq,task-parallel-library
This is my first time working with Parrllel.ForEach and I am having a issue. It is a shame because i really needed performance out of this program and I was getting it. I would say in its last iterations my ForEach is freezing. This is not exposing any error messages....

c#,task-parallel-library
Consider this Task.Run example. It shows how to create a task with cancellation support. I am doing something similar: Task.Run(()=>{while (!token.IsCancellationRequested()) {...}}, token); My questions: Since I already have a reference to the cancellation token, why the purpose of passing it as a parameter to the Task.Run invocation? I often...

php,html,task-parallel-library,opencart,footer
I am trying to edit the footer of my store. But nothing seems to happen. I have to add one more div in the content but it doesn't display on the store, neither the css. <div class="payment col-sm-12"> <div class="container"> <div class="row"> <p> <?php echo $text_payment; ?> </p> </div> </div>...

c#,asynchronous,task-parallel-library,async-await
I have multiple heavy job calculation requests. The job may take different time. By using async and await I want to take the last requested result with canceling eventually unfinished previous tasks. Currently I'm using BackGroundWorker with setting a job ID. I used only the the result with the last...

c#,task-parallel-library,icommand
I've been doing much Googling, and even Bing-ing and I haven't come up with anything that is satisfying. I have a Viewmodel which has some commands, such as a SaveCommand and a NewCommand and a DeleteCommand. My SaveCommand executes a save operation to a file, which I want it to...

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

c#,inheritance,interface,casting,task-parallel-library
Consider a class Foo which wholly implements IFoo. Concurrently, consider a task Task<IFoo>. Why is it that when the following is called, a compilation error is thrown; Task<IFoo> task = Task.Factory.StartNew(() => new Foo()); The compiler states that it cannot convert from source type Task<Foo> to Task<IFoo>. While this makes...

c#,concurrency,task-parallel-library,.net-4.5
This question is in follow up to Why is this code running synchronously? . I realize that my real question is at a higher level than the one in that post. The question I now ask, below, is "how do I accomplish this?" I want to use concurrency in C#...

c#,wpf,listbox,task-parallel-library,backgroundworker
I'm writing a simple application (for testing purposes) that adds 10 M elements to a ListBox. I'm using a BackgroundWorker to do the work and a ProgressBar control to display the progress. Each element is a just a "Hello World!" string with and index that I'm adding during the process....

c#,lambda,task-parallel-library,task
I'm working on a multi-tasking network project and I'm new on Threading.Tasks. I implemented a simple Task.Factory.StartNew() and I wonder how can I do it with Task.Run()? Here is the basic code: Task.Factory.StartNew(new Action<object>( (x) => { // Do something with 'x' }), rawData); I looked into System.Threading.Tasks.Task in Object...

c#,task-parallel-library
Wondering if you could clarify. I am writing a tool that all has todo is retrieve data from a database (sql server) and create txt files. I am talking 500.000 txt files. It's working and all is good. However I was wondering if using Task Parallel library could improve and...