FAQ Database Discussion Community


How to implement an async File.Delete/Create/Move?

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

Getting lower number for elapsed milliseconds when more number of httpwebrequests are created

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

F# task parallelism under mono doesn't “appear” to execute in parallel

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

Task.Start strange behavoir

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

Translate task result

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

Am I doing anything wrong in this async example?

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

TPL async await - does the async Task have to chain up the call stack?

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

How to manage a list of tasks using the Task Parallel Library

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

From IObservable to Task

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# Tasks - Why a noop line is needed in this case

c#,.net,task-parallel-library
I am reading the source code of Interactive Extensions and have found a line that I cannot understand: public static Task<bool> UsingEnumerator(this Task<bool> task, IDisposable disposable) { task.ContinueWith(t => { if (t.IsFaulted) { var ignored = t.Exception; // don't remove! } if (t.IsFaulted || t.IsCanceled || !t.Result) disposable.Dispose(); }, TaskContinuationOptions.ExecuteSynchronously);...

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

To Task.Run or not to Task.Run

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

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

Error handling using delegates

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

ForEachAsyc with Result

c#,linq,task-parallel-library,task
I'm trying to change Stephen Toub's ForEachAsync<T> extension method into an extension which returns a result... Stephen's extension: public static Task ForEachAsync<T>(this IEnumerable<T> source, int dop, Func<T, Task> body) { return Task.WhenAll( from partition in Partitioner.Create(source).GetPartitions(dop) select Task.Run(async delegate { using (partition) while (partition.MoveNext()) await body(partition.Current); })); } My approach...

background thread using Task.Run

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

Task List with parameters

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

How to properly implement asynchronicity in web api 2

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

Task.Run with Parameter(s)?

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

How do I cancel a concurrent heavy Task?

c#,.net,parallel-processing,task-parallel-library,cancellationtokensource
I have a Task by heavy process runs in that's body. In addition, we have no access to the body of this method (heavy process) and we must wait until to completion the process. Now my question is, how do I cancel without interrupting the task so that I do...

Should Parallel.Foreach be waited?

c#,asynchronous,task-parallel-library
A weird thing is happening here. I thought Parallel.Foreach would wait until all of its tasks are complete before moving on. But then, I have something like that: List<string> foo(List<A> list){ Dictionary<string, bool> dictionary = new Dictionary<string, bool>(); Parallel.Foreach(list, element => { dictionary[element.Id] = true; if (element.SomeMethod()){ dictionary[element.Id] = false;...

Adding items to a ListBox in a parallel way

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# Simple TASK Cancel

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

Change DataContext of IQueryable

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

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

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

How to use C# Parallel.For with thread local storage reference type

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

Testing an async ICommand

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

TPL dataflow, MaxDegreeOfParallelism vs load balancing

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

Async call never returns

multithreading,task-parallel-library,async-await
please have a look at below code. public static class DbModel { public static readonly int TableID = 0; static DbModel() { DbModel.PodID = FetchTableID().PodID; } public static Pod FetchTableID() { Pod result = null; try { //Control never comes back from this line. What am I missing? var searchResult...

Task.Run with cancellation support

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

Blocking queue with task

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

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

use Task parallel library for I/O bound processing

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

Thread safe with Linq and Tasks on a Collection

c#,.net,multithreading,task-parallel-library
Given some code like so public class CustomCollectionClass : Collection<CustomData> {} public class CustomData { string name; bool finished; string result; } public async Task DoWorkInParallel(CustomCollectionClass collection) { // collection can be retrieved from a DB, may not exist. if (collection == null) { collection = new CustomCollectionClass(); foreach (var...

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

Task.StartNew() vs Parallel.ForEach : Multiple Web Requests Scenario

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

Creating folders and files in Parallel

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

Using ParallelOptions in Parallel.Foreach for toggling between Serial and Parallel operations

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

TPL Async call within a lambda foreach is not awaited

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

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

captured variables in a parallel.foreach loop

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

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

What are the ContinueWith default values

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# async/await chaining with ConfigureAwait(false)

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

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

How do I run tasks in parallel and select the first result that satisfies a given condition in C#? [duplicate]

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

Task Parallel library waiting for method in loop to finish (.NET 4.0)

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

await Task.Delay(foo); takes seconds instead of ms

c#,.net,task-parallel-library,async-await
Using a variable delay in Task.Delay randomly takes seconds instead of milliseconds when combined with a IO-like operation. Code to reproduce: using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ConsoleApplication { class Program { static void Main(string[] args) { Task[] wait = {...

What is the proper way to delay with cancellation support inside of a task execution delegate?

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

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

Firing off multiple Tasks asynchronously and waiting for them to complete [duplicate]

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

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

Unable to update UI elements when using TPL through nested methods

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

Do I need to consider possible re-entrant coding issues when using the await operator in an extension method?

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

Do I create a deadlock for Task.WhenAll()

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

Executing more than 1000 HTTP request tasks fails

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

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

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

Simple means of making a function non-blocking / async in C#?

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

await with lambda expressions only

c#,.net,task-parallel-library,async-await,c#-5.0
I'm having trouble finding the correct syntax inorder to use await with lambda expressions (anonymous lambda methods). All examples seem to use actual methods declared with the async keyword. Let me describe what I want: ...code in UI thread... Customer cust = null; using (DataContext context = new DataContext()) //...

Footer don't change Opencart

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# variable freshness

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

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

How to create a Task from already asynchronous code?

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

Multiple Parallel.ForEach calls, MemoryBarrier?

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

Why the async await not working as expected

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

Take the Last Requested Async Result and Cancelling Previous Unfinished Tasks

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

Handling Exceptions in Task Parallel library

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

Can a call to Task.GetAwaiter().OnCompleted() fail because of garbage collection?

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

Web API - Set each thread with the HttpRequestMessage id?

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

Update Int32 in Task c#

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

Cleaning up CallContext in TPL

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

Adjust a function for Parallel For in c#

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

ObservableCollection inside a async Task

c#,mvvm,task-parallel-library
I have this strange behaviour of a ObservableCollection inside a task. This works OK: private string status; public string Status { get { return status; } set { SetField<string>(ref status, value); } } public void AddRandomTask() { Task t = Task.Run(async () => { await Randomizer.Instance.LongRandAsync (new MainViewModelObserver(this)); }); t.ContinueWith(m...

TPL Dataflow LinkTo only if no others match

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

Prestashop remove the call us info header

templates,header,task-parallel-library,prestashop
In which module and tpl file I can delete the "call us" info and number phone that appear in the Header template I'm using? Using Prestashop 1.6...

How do I listen to TPL TaskStarted/TaskCompleted ETW events

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

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

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

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

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

How to create a generic Task.ContinueWith extension method

c#,generics,task-parallel-library
So currently I have a Task.ContinueWith extensions method like so: public static Task ContinueWith_UsingSyncContextWorkaround(this Task task, Action<Task> continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler, SynchronizationContext sc) { Action<Task> actionWithWorkaround = t => { SynchronizationContext.SetSynchronizationContext(sc); continuationAction(t); }; return task.ContinueWith(actionWithWorkaround, cancellationToken, continuationOptions,...

Will this implementation using TPL work inside a process running on an STA thread?

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

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

How to cancel Task but wait until it finishes?

c#,.net,multithreading,task-parallel-library
I have threaded task wich performs some operation in loop: static void TaskAction(CancellationToken ct) { while (SomeCondition()) { DoSomeSeriousJob(); ct.ThrowIfCancellationRequested(); } } static void DoSomeSeriousJob() { Console.WriteLine("Serious job started"); Thread.Sleep(5000); Console.WriteLine("Serious job done"); } I start it and then cancel after some period of time: var cts = new CancellationTokenSource();...

Is the following async enabled code liable to cause a deadlock

c#,asynchronous,task-parallel-library,async-await,task
public async Task<Foo> Execute(int id) { var parameters = new { id}; using (var con = new SqlConnection(this.connectionString)) { await con.OpenAsync(); return await con.QueryAsync<foo>( "dbo.uspGetMeFoo", parameters, commandType: CommandType.StoredProcedure, commandTimeout: int.Parse(ConfigurationManager.AppSettings["SqlCommandTimeout"])) .ContinueWith(task => task.Result.FirstOrDefault()); } } This method is awaited on in a calling class, where - some time after...

Parallel.ForEach Freezing during final iterations

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

Should we use ConfigureAwait(false) in libraries that call async callbacks?

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

TPL Dataflow : How to throttle an entire pipeline?

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

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?

Get Completed notification from each task running in parallel

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

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

Assigning a concrete Task to a variable of type Task

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

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

How do I make non-essential computations run in the background?

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

Project a collection as task and wait for all completion

c#,.net,task-parallel-library,async-await
I'm trying to parallelize work issued from a collection, and wait for the completion of all tasks. Here is basically what I have: public Task<int> DoWorkAsync(int arg){ return Task.Factory.StartNew(()=> { Thread.Sleep(1000); return arg*2; }); } public async void DoAllWorks(){ ICollection<int> workToDo = GetSomeWorkFromSomewhere(); IEnumerable<Task<int>> tasks = workToDo.Select(i=> DoWorkAsync(i)); int[] results...

Cancel an async operation after the form has loaded?

c#,winforms,asynchronous,task-parallel-library
I have different classes (implementing an interface) where one method is to perform an async databases search: public async void SearchAsync(CancellationToken ct) { await Task.Run(() => {Find(); }, ct); } private void Find() { //do db search here... } When forms are opened, a background async search is performed to...

How to pass an return value from an aysnchronous method into a synchronous class with a synchronous method

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

Add Numbers by generating random tasks containing numbers [duplicate]

c#,task-parallel-library
This question already has an answer here: Random number generator only generating one random number 7 answers public TestClass{ public Task<int> GetRandomNumber() { return Task.FromResult(new Random().Next(0, 1500)); } } public class Default { static void Main(string[] args) { var test = new TestClass(); List<int> adddata = new List<int>(); for...