-
MY PROJECTS
-
Recent Posts
- SQL.How can you compare two nullable values safely, and how does IS DISTINCT FROM differ from <>?
- SQL.How are NULL values ordered by ORDER BY, how do defaults differ between databases, and how can you control their placement?
- SQL.How does NULL propagate through arithmetic expressions, and how can COALESCE and NULLIF help handle missing values and division by zero?
- SQL.How does NULL affect join conditions, and why can filtering the right-hand table in WHERE remove unmatched rows from a LEFT JOIN?
- SQL.How do GROUP BY and DISTINCT treat NULL values, even though NULL = NULL evaluates to UNKNOWN?
- SQL.How do aggregate functions handle NULL, and what is the difference between COUNT(*), COUNT(column), and COUNT(DISTINCT column)?
- SQL.How does NULL affect IN and NOT IN, and why can NOT EXISTS be a safer choice when a subquery returns nullable values?
- SQL.How do WHERE, HAVING, and CHECK constraints treat conditions that evaluate to UNKNOWN?
- SQL.Why do column = NULL and column <> NULL not work as expected, and when should you use IS NULL and IS NOT NULL?
- SQL.What is SQL’s three-valued logic (TRUE, FALSE, UNKNOWN), and how do AND, OR, and NOT behave with UNKNOWN?
- ChromeDevTools.Watch all failed requests
- SQL.What are domain types (or constraints on data types), and how do they help enforce data correctness?
- SQL.How does SQL handle comparisons between different data types (for example, string vs number), and why is this dangerous?
- SQL.What is the difference between DATE, TIME, TIMESTAMP, and TIMESTAMPTZ, and which one should be used for business events?
- SQL.How do numeric types like INTEGER, BIGINT, DECIMAL, and FLOAT differ in terms of precision and use cases?
- SQL.What problems can arise from implicit type casting in SQL, and how can it affect indexes?
- SQL.How does NULL differ from 0, an empty string, or FALSE in SQL?
- SQL.What is the difference between CHAR, VARCHAR, and TEXT, and when would you choose each?
- SQL.What is MVCC ?
- SQL.What is AutoVacuum Postgres ?
Categories
- Aptana
- Azure
- C#
- DataSnap
- DBExpress
- Delphi
- Delphi и сети
- Delphi. Язык программирования
- ExtJS
- FastReport
- FireDAC
- FireMonkey
- GIT
- ICS
- IDE
- IIS
- Indy
- InnoSetup
- javascript
- jQuery
- JSON
- LiveBindings
- MSHTML
- MySQL
- PHP
- REST
- Ribbons
- SMS
- SQL инструкции
- SVN
- TRichView
- UniGui
- WebBroker
- WinAPI
- Windows
- Алгоритмы
- Без рубрики
- Деревья
- Ищу ответ
- Компонентостроение
- Мои компоненты
- Начальный уровень
- Обработка исключений
- Парсинг
- Потоки(Threads)
- Регулярные выражения
- Тестирование приложений
Category Archives: C#
C#. PLINQ Example
123
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
using System; using System.Linq; public class Example { public static void Main() { var source = Enumerable.Range(100, 20000); // Result sequence might be out of order. var parallelQuery = from num in source.AsParallel() where num % 10 == 0 select num; // Process result sequence in parallel parallelQuery.ForAll((e) => DoSomething(e)); // Or use foreach to merge results first. foreach (var n in parallelQuery) { Console.WriteLine(n); } // You can also use ToArray, ToList, etc as with LINQ to Objects. var parallelQuery2 = (from num in source.AsParallel() where num % 10 == 0 select num).ToArray(); // Method syntax is also supported var parallelQuery3 = source.AsParallel().Where(n => n % 10 == 0).Select(n => n); Console.WriteLine("\nPress any key to exit..."); Console.ReadLine(); } static void DoSomething(int i) { } } |
Posted in C#
Comments Off on C#. PLINQ Example
C#. Simple Parallel Example
Source
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Threading; using System.Drawing; namespace Parallel2 { class Program { public static void Main() { // A simple source for demonstration purposes. Modify this path as necessary. String[] files = System.IO.Directory.GetFiles(@"C:\Users\YellowFriend\Desktop\Pics\Digital-Flame\01", "*.jpg"); String newDir = @"C:\Users\YellowFriend\Desktop\Pics\Digital-Flame\01\Modified"; System.IO.Directory.CreateDirectory(newDir); // Method signature: Parallel.ForEach(IEnumerable<TSource> source, Action<TSource> body) // Be sure to add a reference to System.Drawing.dll. Parallel.ForEach(files, (currentFile) => { // The more computational work you do here, the greater // the speedup compared to a sequential foreach loop. String filename = System.IO.Path.GetFileName(currentFile); var bitmap = new Bitmap(currentFile); bitmap.RotateFlip(RotateFlipType.Rotate180FlipNone); bitmap.Save(Path.Combine(newDir, filename)); // Peek behind the scenes to see how work is parallelized. // But be aware: Thread contention for the Console slows down parallel loops!!! Console.WriteLine("Processing {0} on thread {1}", filename, Thread.CurrentThread.ManagedThreadId); //close lambda expression and method invocation }); // Keep the console window open in debug mode. Console.WriteLine("Processing complete. Press any key to exit."); Console.ReadKey(); } } } |
Posted in C#
Comments Off on C#. Simple Parallel Example
C#. Parallel and Task Example
System.Threading.Tasks.Parallel
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using System.Threading; namespace ParallelExample { public partial class MainForm : Form { private object threadLock = new object(); public MainForm() { InitializeComponent(); } private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { } private void btnProcessImages_Click(object sender, EventArgs e) { ProcessFiles(); // in main thread ProcessFilesParallel(); // in main thread ProcessFilesWithTask(); // << start in additional thread } private void ProcessFiles() // in main thread { string[] files = Directory.GetFiles(@"C:\Users\YellowFriend\Desktop\Pics\Digital-Flame\01", "*.jpg", SearchOption.AllDirectories); string newDir = @"C:\Users\YellowFriend\Desktop\Pics\Digital-Flame\01\ModifiedPictures"; Directory.CreateDirectory(newDir); foreach (string currentFile in files) { string filename = Path.GetFileName(currentFile); using (Bitmap bitmap = new Bitmap(currentFile)) { bitmap.RotateFlip(RotateFlipType.Rotate180FlipNone); bitmap.Save(Path.Combine(newDir, filename)); this.Text = string.Format("Processing {0} on thread {1}", filename, Thread.CurrentThread.ManagedThreadId); } } this.Text = "All done"; } private void ProcessFilesParallel() // in main thread { CheckForIllegalCrossThreadCalls = false; string[] files = Directory.GetFiles(@"C:\Users\YellowFriend\Desktop\Pics\Digital-Flame\01", "*.jpg", SearchOption.AllDirectories); string newDir = @"C:\Users\YellowFriend\Desktop\Pics\Digital-Flame\01\ModifiedPictures"; Directory.CreateDirectory(newDir); Parallel.ForEach(files, currentFile => { string filename = Path.GetFileName(currentFile); using (Bitmap bitmap = new Bitmap(currentFile)) { bitmap.RotateFlip(RotateFlipType.Rotate180FlipNone); bitmap.Save(Path.Combine(newDir, filename)); //this.Text = string.Format("Processing {0} on thread {1}", filename, Thread.CurrentThread.ManagedThreadId); } } ); } private async void ProcessFilesWithTask() { await Task.Factory.StartNew (()=> { CheckForIllegalCrossThreadCalls = false; ProcessFiles(); } ); } } } |
Posted in C#
Comments Off on C#. Parallel and Task Example
C#. Safe and unsafe thread calls to controls
from MSDN
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Threading; namespace ThreadSafeWinControls { public partial class Form1 : Form { public Form1() { InitializeComponent(); } // This event handler creates a thread that calls a // Windows Forms control in an unsafe way. private void button1_Click(object sender, EventArgs e) { UnsafeCall(); SafeCall(); } //------------------ UnSafe call of controls... --------------------- private void UnsafeCall() { CheckForIllegalCrossThreadCalls = false; // Important, if true - exception will be raised Thread demoThread = new Thread(new ThreadStart(this.ThreadProcUnsafe)); demoThread.Start(); } private void ThreadProcUnsafe() { this.textBox1.Text = "This text was set unsafely."; } //------------------ Safe call of controls... --------------------- private delegate void SetTextCallback(string Amessage); // This event handler creates a thread that calls a // Windows Forms control in a thread-safe way. private void SafeCall() { Thread demoThread = new Thread(new ThreadStart(this.ThreadProcSafe)); demoThread.Start(); } // This method is executed on the worker thread and makes // a thread-safe call on the TextBox control. private void ThreadProcSafe() { this.SetText("This text was set safely."); } private void SetText(string text) { // InvokeRequired required compares the thread ID of the // calling thread to the thread ID of the creating thread. // If these threads are different, it returns true. if (this.textBox1.InvokeRequired) { SetTextCallback d = new SetTextCallback(SetText); this.Invoke(d, new object[] { text }); } else { this.textBox1.Text = text; } } } } |
Posted in C#
Comments Off on C#. Safe and unsafe thread calls to controls
C#. ThreadPoolExample
CLR Thread pool – more effective way to manage threads Limitations -only background threads -non identified…
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace ThreadPoolExample { class Program { static void Main(string[] args) { ThreadPoolSomeExample(); } public static void ThreadPoolSomeExample() { Printer p = new Printer(); WaitCallback workItem = new WaitCallback(PrintTheNumbers); for (int i = 0; i < 10; i++) { ThreadPool.QueueUserWorkItem(workItem, p); } Console.WriteLine("All tasks queued"); Console.ReadLine(); } static void PrintTheNumbers(object state) { Printer task = (Printer)state; task.PrintNumbers(); } } public class Printer { private object threadLock = new object(); public void PrintNumbers() { lock (threadLock) { for (int i = 0; i < 10; i++) { Random r = new Random(); Thread.Sleep(1000 * r.Next(5)); Console.Write("{0},", i); } Console.WriteLine(); } } } } |
Posted in C#
Comments Off on C#. ThreadPoolExample
C#. Timer and threads
Some task that can be periodically called by timer in thread
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace TimerExample { class Program { static void Main(string[] args) { Console.WriteLine("Working with Timer type\n"); TimerCallback timeCB = new TimerCallback(PrintTime); Timer t = new Timer(timeCB,"Hello from Main",0,1000); // Timer thread... Console.WriteLine("Hit to terminate..."); Console.ReadLine(); } static void PrintTime(object state) { Console.WriteLine("Time is:{0}",DateTime.Now.ToLongTimeString()); } } } |
Posted in C#
Comments Off on C#. Timer and threads
C#. Threads Synchronization
No synchronization example – full chaos during execution…
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace ThreadsSync { class Program { static void Main(string[] args) { StartManyThreadsNoSynchronization(); } static void StartManyThreadsNoSynchronization() { Printer p = new Printer(); Thread[] threads = new Thread[10]; for (int i = 0; i < 10; i++) { threads[i] = new Thread(new ThreadStart(p.PrintNumbers)); threads[i].Name = string.Format("Worker thread #{0}",i); } foreach (Thread t in threads) t.Start(); Console.ReadLine(); } } public class Printer { public void PrintNumbers() { for (int i = 0; i < 10; i++) { Random r = new Random(); Thread.Sleep(1000 * r.Next(5)); Console.Write("{0},",i); } Console.WriteLine(); } } } |
Synchronized with lock example
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace ThreadsSync { class Program { static void Main(string[] args) { StartManyThreads(); } static void StartManyThreads() { Printer p = new Printer(); Thread[] threads = new Thread[10]; for (int i = 0; i < 10; i++) { threads[i] = new Thread(new ThreadStart(p.PrintNumbers)); threads[i].Name = string.Format("Worker thread #{0}", i); } foreach (Thread t in threads) t.Start(); Console.ReadLine(); } } public class Printer { private object threadLock = new object(); public void PrintNumbers() { lock (threadLock) { for (int i = 0; i < 10; i++) { Random r = new Random(); Thread.Sleep(1000 * r.Next(5)); Console.Write("{0},", i); } Console.WriteLine(); } } } } |
Synchronized with Monitor System.Threading.Monitor has more options like Monitor.Pulse(), Monitor.PulseAll()
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace ThreadsSync { class Program { static void Main(string[] args) { StartManyThreads(); } static void StartManyThreads() { Printer p = new Printer(); Thread[] threads = new Thread[10]; for (int i = 0; i < 10; i++) { threads[i] = new Thread(new ThreadStart(p.PrintNumbers)); threads[i].Name = string.Format("Worker thread #{0}", i); } foreach (Thread t in threads) t.Start(); Console.ReadLine(); } } public class Printer { private object threadLock = new object(); public void PrintNumbers() { Monitor.Enter(threadLock); try { for (int i = 0; i < 10; i++) { Random r = new Random(); Thread.Sleep(1000 * r.Next(5)); Console.Write("{0},", i); } Console.WriteLine(); } finally { Monitor.Exit(threadLock); } } } } |
Also possible synchronization with System.Threading.Interlocked and [Synchronization] attribute, which is below, class should be … Continue reading
Posted in C#
Comments Off on C#. Threads Synchronization
C#. Foreground and background threads
Foreground thread – thread that is critical, application will not end up to thread will not be finished. Background thread – not critical, it can be interrupted during application close example
|
1 2 3 4 |
Thread backgroundThread = new Thread(new ThreadStart(p.PrintNumbers)); backgroundThread.Name = "Secondary"; backgroundThread.IsBackground = true; // <<< Background thread !!! backgroundThread.Start(); |
Posted in C#
Comments Off on C#. Foreground and background threads
C#. Creating own threads
example shows – thread statictics -start thread without params -start thread with params -waiting of Thread which starts other threads… with AutoResetEvent handle
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using System.Windows.Forms; namespace ThreadStats { class Program { private static AutoResetEvent waitHandle = new AutoResetEvent(false); static void Main(string[] args) { //PrimaryThreadStats(); // ThreadStartExample(); ThreadStartWithParams(); } public static void ThreadStartExample() { Console.WriteLine("*** Amasing Thread App ***\n"); Console.Write("Do you want [1] or [2] threads?"); string threadCount = Console.ReadLine(); Thread primaryThread = Thread.CurrentThread; primaryThread.Name = "Primary"; Console.WriteLine("-> {0} is executing Main()", Thread.CurrentThread.Name); Printer p = new Printer(); switch (threadCount) { case "2": Thread backgroundThread = new Thread(new ThreadStart(p.PrintNumbers)); backgroundThread.Name = "Secondary"; backgroundThread.Start(); waitHandle.WaitOne(); // << main thread will wait !!! break; case "1": p.PrintNumbers(); break; default: Console.WriteLine("I don't know what you want you get 1 thread"); goto case "1"; } MessageBox.Show("I am buisy!", "Work on main thread..."); Console.ReadLine(); } public class Printer { public void PrintNumbers() { Console.WriteLine("-> {0} is executing PrintNumbers()",Thread.CurrentThread.Name); Console.WriteLine("Your Numbers:"); for (int i = 0; i < 10; i++) { Console.Write("{0}, ",i); Thread.Sleep(2000); } Console.WriteLine(); waitHandle.Set(); // stop waiting for waiting thread } } static void PrimaryThreadStats() { Thread t = Thread.CurrentThread; t.Name = "PrimaryThread"; Console.WriteLine("Name of current AppDomain:{0}",Thread.GetDomain().FriendlyName); Console.WriteLine("ID of current context:{0}", Thread.CurrentContext.ContextID); Console.WriteLine("ThreadName:{0}", t.Name); Console.WriteLine("Is Alive?:{0}", t.IsAlive); Console.WriteLine("Priority:{0}", t.Priority); Console.WriteLine("ThreadState:{0}", t.ThreadState); Console.ReadLine(); } class AddParams { public int a, b; public AddParams(int n1,int n2) { a = n1; b = n2; } } static void Add(object data) { if (data is AddParams) { Console.WriteLine("ID of thread in Add():{0}",Thread.CurrentThread.ManagedThreadId); AddParams p = (AddParams)data; Console.WriteLine("{0}+{1} is {2}",p.a,p.b,p.a+p.b); waitHandle.Set(); } } public static void ThreadStartWithParams() { AddParams p = new AddParams(10, 10); Thread t = new Thread( new ParameterizedThreadStart(Add)); t.Start(p); //Thread.Sleep(5); // rough approach waitHandle.WaitOne(); Console.WriteLine("Other thread is done"); Console.ReadLine(); } } } |
Posted in C#
Comments Off on C#. Creating own threads
C#. System.Threading and other examples
System.Threading and System.Threading.Thread main types to work with threads directly example
|
1 2 3 4 5 6 7 8 9 10 11 12 |
static void PrimaryThreadStats() { Thread t = Thread.CurrentThread; t.Name = "PrimaryThread"; Console.WriteLine("Name of current AppDomain:{0}",Thread.GetDomain().FriendlyName); Console.WriteLine("ID of current context:{0}", Thread.CurrentContext.ContextID); Console.WriteLine("ThreadName:{0}", t.Name); Console.WriteLine("Is Alive?:{0}", t.IsAlive); Console.WriteLine("Priority:{0}", t.Priority); Console.WriteLine("ThreadState:{0}", t.ThreadState); Console.ReadLine(); } |
During debugging… we can see what is happening to threads… Debug > Windows > Threads ThreadStart Example
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using System.Windows.Forms; // add reference to System.Windows.Forms.dll namespace ThreadStats { class Program { static void Main(string[] args) { //PrimaryThreadStats(); Console.WriteLine("*** Amasing Thread App ***\n"); Console.Write("Do you want [1] or [2] threads?"); string threadCount = Console.ReadLine(); Thread primaryThread = Thread.CurrentThread; primaryThread.Name = "Primary"; Console.WriteLine("-> {0} is executing Main()", Thread.CurrentThread.Name); Printer p = new Printer(); switch (threadCount) { case "2": Thread backgroundThread = new Thread(new ThreadStart(p.PrintNumbers)); backgroundThread.Name = "Secondary"; backgroundThread.Start(); break; case "1": p.PrintNumbers(); break; default: Console.WriteLine("I don't know what you want you get 1 thread"); goto case "1"; } MessageBox.Show("I am buisy!","Work on main thread..."); Console.ReadLine(); } public class Printer { public void PrintNumbers() { Console.WriteLine("-> {0} is executing PrintNumbers()",Thread.CurrentThread.Name); Console.WriteLine("Your Numbers:"); for (int i = 0; i < 10; i++) { Console.Write("{0}, ",i); Thread.Sleep(2000); } Console.WriteLine(); } } static void PrimaryThreadStats() { Thread t = Thread.CurrentThread; t.Name = "PrimaryThread"; Console.WriteLine("Name of current AppDomain:{0}",Thread.GetDomain().FriendlyName); Console.WriteLine("ID of current context:{0}", Thread.CurrentContext.ContextID); Console.WriteLine("ThreadName:{0}", t.Name); Console.WriteLine("Is Alive?:{0}", t.IsAlive); Console.WriteLine("Priority:{0}", t.Priority); Console.WriteLine("ThreadState:{0}", t.ThreadState); Console.ReadLine(); } } } |
Posted in C#
Comments Off on C#. System.Threading and other examples