C#.Rihter.Timer
simple example, task will be created periodically and will be handled in thread pool with Thread.QueueUserWorkItem
var timer = new Timer( (o) => {
simple example, task will be created periodically and will be handled in thread pool with Thread.QueueUserWorkItem
var timer = new Timer( (o) => {
simple example
int[] nums = Enumerable.Range(1, 10).ToArray(); var res = nums.AsParallel().Where(n => n < 5).ToArray(); Thread.Sleep(2000); Console.WriteLine(String.Join(» «, res));
output
1 2 3 4
tasks that can be done in parallel
static void Main(string[] args) { Parallel.For(1, 10, i => DoWork(i)); Thread.Sleep(12000); } static void DoWork(int i) {
static void Main(string[] args) { Task<int> t = new Task<int>(() => { Console.WriteLine(«smth in thread»); return 123; }); Console.WriteLine(t.Status); t.Start(); Console.WriteLine(t.Status); Thread.Sleep(3000); Console.WriteLine(t.Status); }
Example
static void Main(string[] args) { Task<Int32[]> parent = new Task<Int32[]>(() => { var results = new Int32[3]; StartNewTask(results, 0, 1); StartNewTask(results, 1, 2);
Два года тому назад я писал о получении в программе значения первичного ключа, который сгенерирован СУБД при добавлении новой строки в таблицу. Мои примеры вызова
static void Main(string[] args) { Task<int> t = new Task<int>(Work); t.Start(); Thread.Sleep(3000); // doing smth in main thread t.ContinueWith(t => Console.WriteLine(«job is done «
task allows get result
static void Main(string[] args) { Task<int> t = new Task<int>(n => Sum((int) n), 10000); t.Start(); t.Wait(); Console.WriteLine(«The sum is «
how do i exit from thread
static void Main(string[] args) { var tokenSource = new CancellationTokenSource(); ThreadPool.QueueUserWorkItem(o => ThreadWorker(tokenSource.Token, 1000)); Console.WriteLine(«Press <Enter> to cancel
static void Main(string[] args) { Console.WriteLine(«this is main thread»); ThreadPool.QueueUserWorkItem(ThreadWorker, 123); Thread.Sleep(3000); } private static void ThreadWorker(object obj) { Thread.Sleep(1000); Console.WriteLine(«hi from thread pool