Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
6.3 Parallelism: job-pattern
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Clojure
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Rust
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
//6.3 Parallelism: job-pattern using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Net; using System.Threading; namespace Rextester { public class Program { public static void Main(string[] args) { //Not sure if I could call this pattern or that it's not called something else already //But this is what I use and it's very convinient //The point is to define a class (a job) whose instances would be used one for each thread. //This way it's easy to monitor threads and their outcome and also pass any parameters to them. List<string> urls = new List<string>() { "http://google.com", "http://google.lt", "httpp://google.lt" }; List<Job> jobs = new List<Job>(); foreach(var url in urls) { var job = new Job(); jobs.Add(job); ThreadPool.QueueUserWorkItem(f => job.DoWork(url)); } while(jobs.Any(f => !f.IsDone)) { Thread.Sleep(1000); } foreach(var job in jobs) { Console.WriteLine(string.IsNullOrEmpty(job.Error) ? job.Result.Substring(0, 50) + "..." : job.Error); } } } public class Job { public bool IsDone { get; set; } public string Result { get; set; } public string Error { get; set; } public void DoWork(string url) { try { WebClient client = new WebClient(); Result = client.DownloadString(url); } catch(Exception e) { Error = e.InnerException != null ? e.InnerException.Message : e.Message; } finally { IsDone = true; } } } }
Show compiler warnings
[
+
]
Show input
Compilation time: 0.19 sec, absolute running time: 2.11 sec, cpu time: 0.56 sec, average memory usage: 28 Mb, average nr of threads: 14
edit mode
|
history
|
discussion