Podcast #128: We chat with Kent C Dodds about why he loves React and discuss what life was like in the dark days before Git. Listen now.
35

You're not seeing 95 threads because of how Tasks work. The documentation for the Task class says that "tasks typically run asynchronously on a thread pool thread". The thread pool will limit how many tasks will run at one time, so when you call task.Start() when the pool has reached its limit that task won't start executing until one of the pool threads ...


25

Assumption of a possible bug I assume that you only have tested this with a password which length is the same as Math.Max(startPassword.Length, endPassword.Length); and if that is true I think this won't work if you won't know the length of the password. The int[] array has the same length as the result of the Max() call and each overlapping will be ...


21

Just fire the task without async/await. private void InitMethod(ServiceControl serviceControl) { if (serviceControl != null) { Task.Factory.StartNew(() => serviceControl.Execute()); } } In a proper F&F task all exception handling (including a final catch, logging, notifications) is done by the task itself, so you don't need ...


18

There are several ways to achieve what you're after and it depends on whether you want the results drip fed to you as they're available or whether you're happy to have them all in one bang. The way you've implemented your method gives it all in one bang - which is fine. A shorter implementation could be public static async Task<IEnumerable<T>> ...


14

int count = remainingTasks.Count(); Since remainingTasks is a List, you can use the Count property here. var exceptions = new List<Exception>(); This variable should be declared where it's used: in the if Interlocked.Decrement block. if (task1.IsFaulted) This means you're treating canceled tasks the same as successfully completed ones. Instead, ...


14

Passing the CancellationToken to the Task constructor allows Cancel() to work only if the task has not yet started. Also pass the token into CalculatePassword() and check it every loop iteration: while (true) { token.ThrowIfCancellationRequested(); // ... } Accessing Task.Result ends up calling Task.Wait(). So you're waiting for any task to be ...


11

I like how you've written this code. Just a couple of nitpicks: Consistency with var var remainingTasks = tasks.ToList(); int count = remainingTasks.Count(); var exceptions = new List<Exception>(); Why not use var to declare count? Seems pretty obvious to me that remainingTasks.Count() would be an int, and it's the only explicitly typed ...


11

I think that your limit checking is a little obscure. Why are the constants defined in the constructor? They're related to your class, not to your constructor. If I were to be able to change the Width or Height someday, I'd need these constants to validate that my new values are still "legit". You might want to look at the Contract class in the .Net ...


11

Just noticed this private Section[] GetHoriztonalSections() which is IMO correct, but this private short[] GenerateSection(Section section) should be named somehow different, because it isn't generating a Section. public void SaveImage(string filename, ImageFormat imageFormat) this should be improved by not using SetPixel() because it is ...


11

Three programmers are ordering Christmas presents online. The first programmer orders a present, and goes to wait by the mailbox. He waits there for 24 hours until the first present arrives. He takes the present inside, orders a second present, and heads out to wait by the mailbox again. This goes on for several days until all his presents have arrived. ...


10

Your catch statement is catching any error (EVERY ERROR), which is not a good thing. I assume there are several errors that you are anticipating, but you shouldn't catch them all. You will run into bugs and won't know what is going on because the errors will be bulked into your cancellation. I would catch only the exceptions that you know about and are ...


10

No, when you use the lock like that, it's completely useless. Each lock would get its own identifier, so none of he locks would keep any other thread out. To make the lock work at all, you need to use the same identifier for all locks. Demonstration: object sync = new Object(); var keytofind = rawDataMeasure.RateKey.ToString(CultureInfo.InvariantCulture); ...


9

Not exactly a review, but since you are asking for simpler way... The simpler way is to run your tasks via dispatcher. Just run it on background thread: _thread = new Thread(() => { _dispatcher = Dispatcher.CurrentDispatcher; Dispatcher.Run(); }); _thread.Start(); And use _dispatcher....


9

Instead of checking the time from each thread on each iteration, I would use a Timer: int count = 0; TimeSpan reportPeriod = TimeSpan.FromMinutes(0.1); using (new Timer( _ => Console.WriteLine("{0}: Extracted {1} urls", DateTime.Now, count), null, reportPeriod, reportPeriod)) { Parallel.ForEach( list, tuple => { ...


8

Yes, what you are doing is a problem. List is not thread-safe and adding items from multiple threads can lead to data corruption (for example individual elements overwriting each other). You said that you don't care about the order of items inserted quickest fix is to use ConcurrentBag Another option is to the PLINQ extensions and use the Select extension ...


8

using Task = System.Threading.Tasks.Task; using Thread = System.Threading.Thread; using Barrier = System.Threading.Barrier; using Monitor = System.Threading.Monitor; using IDisposable = System.IDisposable; You don't need to write all those usings one class at a time. In C#, the common approach is to add a using once for each namespace you need. This is ...


8

This doesn't address your actually question (simplifying the logic/implementation), but I feel like it's important. For the sake of readability, I would recommend replacing some of the nested lambdas with a function reference to a named methods. The assignment to globals in the first section of code has 5 levels of indentation. That is a bit much for an ...


7

public interface FtpItem By convention, interface names in .net start with a capital i, so the expected name for that type would be IFtpItem. The interface has quite a few members, which points toward too many responsibilities. In particular, the SortedList<string, FtpItem> List { get; } member smells. ...and the implementation confirms the doubt: ...


6

Your code is absolutely correct in case when you want to start workflows only when all of them are configured. But if you want to start each workflow once it's configured (independently from other workflows) then it might be a good idea to use continuations... In .NET 4.5 it would look like this: public sealed class Engine : IEngine { private readonly ...


6

As the latecomer to the party, I'll take it from V3... First, async void should only be used for event handlers. I'd much rather see Start return a Task representing the listening loop. For a simple example, you don't need to do any cleanup at all. Once your app exits, the OS will clean up after it. Doing cleanup just before application exit is just a ...


6

It does show very good example for the progressbar in WinForms. Here are my code-review outputs for you. Closebutton_Click calls the other click "handlers". This is not the common way. Implement another method and call it from those handlers. I couldnt understand the logic why are you asking the cancellation before and after invoking the DoSomething(). ...


6

private readonly TimeSpan _maxPeriod; private readonly System.Threading.SemaphoreSlim _throttleActions, _throttlePeriods; I would add using System.Threading; at the top of the code file, so as to avoid having to fully qualify everything you're referencing in that namespace. Also, at a glance (especially with the fully qualified SemaphoreSlim) it looks like ...


6

Classes are internal by default then you do not need to explicitly declare them internal, moreover until you do not need to add a derived class you can mark them sealed. sealed class Manga { } Public properties are, usually, in title case then, for example: mainUrl should be MainUrl. Also note that you may simply use Url. In my opinion Dictionary<...


6

It's not at all clear to me what the point of this code is: I assume it's running on the server, but I can't see how it would fit into the broader picture of client-server synch. It would probably be better to debug the underlying problem rather than try to hack a workaround. That aside, the code has one important misunderstanding, one bad practice used ...


6

if (TaskCancellation == true) { break; } CancellationToken.ThrowIfCancellationRequested(); Some comments explaining why two different cancellation methods are necessary would be useful. if (jockey.Name != null) { lock (((...


5

You shouldn't usually use Task constructor directly, use Task.Factory.StartNew (or Run). I also don't understand why you want to have a separate method for starting a task. It is completely superficial. It's just as useless as adding Print method that calls Console.WriteLine instead of using Console.WriteLine directly. Normally, you just do this: void ...


5

You may want to be using CancellationTokens via the overload for the async methods of the ClientWebSocket class to properly cleanup tasks on exit. 1024 is usually the value I like to use for web connectivity, the MTU (Maximum Transmission Unit)1 for Ethernet is 1500 bytes, and I like to round that down to a near exponent of 2, in this case 2^10. I'm not all ...


5

public async Task<bool> Process(Core.MessageInfo MessageItem) { //Start new task to process the message bool _ProcessedResult = await Task<bool>.Factory.StartNew(() => MessageProcesser(MessageItem), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); return _ProcessedResult; } That's a weird name for a ...


5

I had a similar problem. Here is an easy way to make all your tasks run exclusively on one thread for all tasks. And you can also run the them Concurrently to using Scheduler.ConcurrentScheduler. ConcurrentExclusiveSchedulerPair Scheduler = new ConcurrentExclusiveSchedulerPair(); Task.Factory.StartNew(() => { ...


5

TryExecuteTaskInline is used in what is called "task inlining": basically, when you call Wait() on a Task that didn't start executing yet, it might be executed on the current thread. A simple way to test that is: var factory = new TaskFactory(new SequentialScheduler()); factory.StartNew( () => { factory.StartNew(() => { }).Wait(); ...


Only top voted, non community-wiki answers of a minimum length are eligible