All Questions

Filter by
Sorted by
Tagged with
221 votes
6 answers
98k views

What's the difference between Task.Start/Wait and Async/Await?

I may be missing something but what is the difference between doing: public void MyMethod() { Task t = Task.Factory.StartNew(DoSomethingThatTakesTime); t.Wait(); UpdateLabelToSayItsComplete(); }...
Jon's user avatar
  • 39.5k
190 votes
5 answers
119k views

Async/await vs BackgroundWorker

In the past few days I have tested the new features of .net 4.5 and c# 5. I like its new async/await features. Earlier I had used BackgroundWorker to handle longer processes in the background with ...
Tom's user avatar
  • 3,999
149 votes
6 answers
199k views

Run two async tasks in parallel and collect results in .NET 4.5

I've been trying for a while to get something I thought would be simple working with .NET 4.5 I want to fire off two long running tasks at same time and collect the results in in the best C# 4.5 (...
Simon_Weaver's user avatar
103 votes
3 answers
83k views

Proper way to implement a never ending task. (Timers vs Task)

So, my app needs to perform an action almost continuously (with a pause of 10 seconds or so between each run) for as long as the app is running or a cancellation is requested. The work it needs to do ...
Josh's user avatar
  • 2,103
28 votes
1 answer
26k views

Passing a task as parameter

I am not sure whether this is possible, so here me out: I have a sequence of action to perform multiple async Task MethodA(...) { // some code // a call to specific Async IO bound method ...
Goran's user avatar
  • 6,398
27 votes
2 answers
6k views

Task.WhenAny and Unobserved Exceptions

Let's say I have three tasks, a, b, and c. All three are guaranteed to throw an exception at a random time between 1 and 5 seconds. I then write the following code: await Task.WhenAny(a, b, c); This ...
David Pfeffer's user avatar
23 votes
3 answers
1k views

When to use the "await" keyword

I'm writing a web page, and it calls some web services. The calls looked like this: var Data1 = await WebService1.Call(); var Data2 = await WebService2.Call(); var Data3 = await WebService3.Call(); ...
Eric B's user avatar
  • 4,417
20 votes
4 answers
19k views

Task.WaitAll not waiting for task to complete

While trying to figure out the new (maybe not so new now, but new to me, anyway) Task asynchronous programming in C#, I ran into a problem that took me a bit to figure out, and I'm not sure why. I ...
cjk84's user avatar
  • 357
17 votes
3 answers
14k views

Why does Task.Delay() allow an infinite delay?

After my application froze I tracked down the cause to a thread waiting on a task created by Task.Delay() (or TaskEx.Delay() in .NET 4.0) for which it provided a computed TimeSpan that, due to a bug, ...
Allon Guralnek's user avatar
16 votes
3 answers
7k views

.NET 4 equivalent of Task.WhenAll()

In .NET 4, is there any functional equivalent to .NET 4.5's System.Threading.Tasks.Task.WhenAll()? The goal is to wrap up multiple async tasks into a single one that is completed when all of its ...
kpozin's user avatar
  • 26.4k
16 votes
1 answer
585 views

.Net 4.5 killed my TPL, now what?

Exhibit 1: some code wrapping an Async (not async!) network call into a Task public static Task<byte[]> GetAsync(IConnection connection, uint id) { ReadDataJob jobRDO = new ReadDataJob(); ...
Benjol's user avatar
  • 65.2k
15 votes
1 answer
10k views

.Net 4.5 Svcutil generates two operations with the same name (Method and MethodAsync)

I am consuming a predefined wsdl with svcutil a la: svcutil some_service.wsdl one of the methods generated has the following signature: [System.ServiceModel.OperationContractAttribute(Action="http:/...
vossad01's user avatar
  • 11.8k
14 votes
3 answers
12k views

Where does an async Task throw Exception if it is not awaited?

I have the following example: (please also read comments in code, as it will make more sense ) public async Task<Task<Result>> MyAsyncMethod() { Task<Result> resultTask = ...
Dan Dinu's user avatar
  • 33k
13 votes
2 answers
338 views

Task.Run in Static Initializer

Consider the following code. static class X { public static int Value = Task.Run(() => 0).Result; } class Program { static void Main(string[] args) { var value = X.Value; }...
Timothy Shields's user avatar
11 votes
2 answers
5k views

Can a Task have multiple awaiters?

I am toying around with an async service for a Windows 8 project and there are some async calls of this service, which should only be called once at a time. public async Task CallThisOnlyOnce() { ...
user avatar
11 votes
1 answer
4k views

Async CTP - Recommended approach for task scheduling

I'm currently working on a largely asynchronous application which uses TAP throughout. Every class which has methods for spawning Tasks also has a TaskScheduler injected into it. This allows us to ...
Lawrence Wagerfield's user avatar
10 votes
1 answer
5k views

Exception handling in fire and forget for C# 5 (in .net 4.5)

Consider the following "fire-and-forget" use case: A caller requests some data from my method. My method checks the cache to see if the data is already there. If it's not, it fetches it from the ...
Bill Sourour's user avatar
  • 1,188
10 votes
2 answers
2k views

Task not garbage collected

In the following program, I'd expect the task to get GC'd, but it doesn't. I've used a memory profiler which showed that the CancellationTokenSource holds a reference to it even though the task is ...
Eli Arbel's user avatar
  • 22.6k
9 votes
1 answer
3k views

Customizing ActionBlock<T>

I want to implement a prioritised ActionBlock<T>. So that i can Conditionally give priority to some TInput items by using a Predicate<T>. I read Parallel Extensions Extras Samples and ...
Rzassar's user avatar
  • 2,193
8 votes
2 answers
1k views

What is the purpose of passing CancellationToken to Task.Factory.StartNew()

In the following code a CancellationToken is passed to the .StartNew(,) method as the 2nd parameter, but is only usable by the Action via the closure in the lambda. So, what is the purpose of passing ...
Sean B's user avatar
  • 11.4k
8 votes
4 answers
2k views

Why does the localInit Func get called multiple times per thread in Parallel.ForEach

I was writing some code to process a lot of data, and I thought it would be useful to have Parallel.ForEach create a file for each thread it creates so the output doesn't need to be synchronized (by ...
Mike's user avatar
  • 1,558
7 votes
3 answers
6k views

async/await. Where is continuation of awaitable part of method performed?

I am really curious how async/await enables your program not to be halted. I really like the way how Stephen Cleary explains async/await: "I like to think of "await" as an "asynchronous wait". That is ...
StepUp's user avatar
  • 37.3k
7 votes
5 answers
726 views

Unwrapping IObservable<Task<T>> into IObservable<T> with order preservation

Is there a way to unwrap the IObservable<Task<T>> into IObservable<T> keeping the same order of events, like this? Tasks: ----a-------b--c----------d------e---f----> Values: ----...
yallie's user avatar
  • 2,350
7 votes
3 answers
4k views

Task.Factory.ContinueWhenAny continue when any task finish without exception

I have 3 tasks in my application that are responsible for getting data from databases. Till now I had all tasks executed one after one. If first finished and had Result then this was my data, if now I ...
Misiu's user avatar
  • 4,857
7 votes
1 answer
413 views

What other silent changes did happen from .Net Frameworkf v.4.0 to 4.5? [closed]

We want to switch to .net 4.5 cause it offers many improvements. But...sometimes I found some tricky details about not trivial changes in the framework. Lets look for TPL unobserved exception ...
Pavel Voronin's user avatar
7 votes
2 answers
2k views

Multi-Threading a Large C# Application Using async/await

All, I have been given the job to multi-thread a large C# application. To do this I have chosen to go use async/await. I am well aware of the use of IProgress<T> to report progress to the UI (...
MoonKnight's user avatar
  • 23.5k
6 votes
1 answer
4k views

Task Parallel Library Code Freezes in a Windows Forms Application - Works fine as a Windows Console Application

This question is a follow-up to a previous question that I had asked: How to Perform Multiple "Pings" in Parallel using C# I was able to get the accepted answer (a Windows console ...
HydroPowerDeveloper's user avatar
6 votes
2 answers
2k views

What in the Rx Framework allows me to return an IObservable<T> while awaiting other methods during creation?

I've been working on creating an IObservable<T> implementation using the Reactive Extensions for Twitter's streaming APIs. From a high level an HTTP request is sent and the connection is kept ...
casperOne's user avatar
  • 74.1k
6 votes
2 answers
2k views

Is TPL DataFlow included with either .NET 4.5 or .NET 4.5.1?

I'm confused. We upgraded our project recently to .NET 4.5.1. We installed .NET 4.5.1 on our servers. I'm referencing assembly System.Threading.Tasks.Dataflow from the GAC at C:\windows\Microsoft....
Steve Dunn's user avatar
  • 21.4k
6 votes
2 answers
5k views

How to implement continuously running dataflow blocks in TPL?

I have producer/consumer dataflow block set-up using BufferBlock and ActionBlock and it is working fine inside Console application; After adding all items into BurfferBlock and Linking BufferBlock ...
user2757350's user avatar
5 votes
2 answers
5k views

Is it possible to cancel a C# Task without a CancellationToken?

I'm need to cancel an API call that returns a Task, but it doesn't take a CancellationToken as a parameter, and I can't add one. How can I cancel that Task? In this particular case, I'm using ...
TimF's user avatar
  • 151
5 votes
4 answers
6k views

List of objects with async Task methods, execute all concurrently

Given the following: BlockingCollection<MyObject> collection; public class MyObject { public async Task<ReturnObject> DoWork() { (...) return await ...
Alex's user avatar
  • 76.7k
5 votes
1 answer
2k views

Task continuations always run even when specifying TaskContinuationOptions

I want to run some code when an async task completes successfully. From reading documentation and examples on the web, I thought I could use Task.ContinueWith and specify TaskContinuationOptions....
corvuscorax's user avatar
  • 5,890
5 votes
1 answer
4k views

Is CancellationTokenSource.CancelAfter() leaky?

The release of the Async Targeting Pack prompted me to use ILSpy to have a look at what Task-based Asynchronous Pattern (TAP) extension methods were provided there (some of which I have already ...
Allon Guralnek's user avatar
4 votes
4 answers
4k views

What is the best way to return completed Task?

What is the best way to return a completed Task object? It is possible to write Task.Delay(0), or Task.FromResult<bool>(true) whatever. But what is the most efficient way?
XperiAndri's user avatar
  • 1,140
4 votes
4 answers
2k views

Create reusable processing logic on top of predefined blocks with TPL dataflow?

I love TPL dataflow. Well, an interesting design choice is that, most predefined block use Delegates to allow us to implement processing logic. That looks good in simple scenarios. But let's think ...
Dodd's user avatar
  • 530
4 votes
1 answer
2k views

Cold Tasks and TaskExtensions.Unwrap

I've got a caching class that uses cold (unstarted) tasks to avoid running the expensive thing multiple times. public class AsyncConcurrentDictionary<TKey, TValue> : System.Collections....
Fowl's user avatar
  • 5,038
4 votes
2 answers
6k views

return Task.ContinueWith<TResult>() without knowing TResult

How do I create and return a continuation Task using reflection or by any other means if I only have access the Task? I need a way to let an exception in the continuation travel back to the original ...
Tersius's user avatar
  • 267
4 votes
1 answer
731 views

Async CTP - Ambient CancellationToken and IProgress

Bearing in mind the Async CTP promotes implicit scheduling via an ambient SynchronizationContext, is there any reason why I should not make my CancellationToken and IProgress ambient too? I'm ...
Lawrence Wagerfield's user avatar
4 votes
1 answer
82 views

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

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 ...
philologon's user avatar
  • 2,093
4 votes
0 answers
830 views

CallContext - What are the recommendations for using this going forwards? [closed]

Does anyone know if there's any planned support in upcoming versions of .NET for storing objects in the ambient execution context? There's a definite need for it, as highlighted in the following pages:...
Lawrence Wagerfield's user avatar
3 votes
2 answers
3k views

Writing to a file from multiple threads without lock

I need to write data buffer by buffer in to a file from different threads. To avoid locking I am writing into different files, say 'file_1','file_2' and at last merges all these files to 'file'. Is ...
user1884330's user avatar
3 votes
3 answers
2k views

async Methods correct? Resharper warning

in my Method RecalcChartAsync i do some time intensive stuff.. so i thought i'll do some things async. I want to start the two Methods CreateHistogramAsync CalculatePropValuesAsync and in the ...
JuHwon's user avatar
  • 2,053
3 votes
4 answers
1k views

Correct usage of Async/Await for Multiple Tasks To Db

I have a simple scenario but I would like to know if my approach is correct, is it better advised to chose a single task to save my failed orders or can i kick off and fire off multiple tasks and wait ...
IbrarMumtaz's user avatar
  • 4,334
3 votes
1 answer
5k views

Best way to make send bulk emails parallel

I am new to TPL (Task Parallel Library) and I'm having a hard time trying to configure my process to run tasks in parallel. I'm working on an application to send bulk emails (like thousands per minute,...
Silvestre's user avatar
  • 844
3 votes
2 answers
1k views

How to use async/await with a library that uses an event-based asynchronous pattern?

I use a library that has an asynchronous method called DoWork(...) that will raise a WorkDone event when the operation completes. I would like to write a method that calls this library, but instead ...
Xavier Poinas's user avatar
3 votes
2 answers
3k views

TaskEx.Yield(TaskScheduler)

Last month I asked the following question which resulted in my learning of TaskEx.Yield: Can async methods have expensive code before the first 'await'? However, I have since realized that ...
Lawrence Wagerfield's user avatar
3 votes
5 answers
2k views

Howto: Parallel.Foreach executes many processes, after each process run a new process (but one at a time)? [closed]

I'm sure someone knows this and I will be very thankful for the answer. I don't know much about delegates and asynch and the like - so please give me a general example of how I could implement. I ...
shawn.mek's user avatar
  • 1,215
3 votes
1 answer
142 views

The Mysterious "usage" Tag in Visual Studio Documentation XML Comment Tags

I often use XML documentation to document my classes, methods and properties but take a look at this method from Microsoft: Usage? What kind of sorcery is this? How does one emulate this wizardry? ...
bokibeg's user avatar
  • 2,101
3 votes
3 answers
2k views

In parallel call, limit executions per second

Using TPL / Parallel.ForEach is there an out-of-the-box way to limit the number of times a method is called per unit of time (i.e. no more than 50 calls per second). This is different than limiting ...
Suraj's user avatar
  • 36.3k