Образец заголовка Образец текста –Второй уровень Третий уровень –Четвертый уровень »Пятый уровень Тема: Task Parallel Library Крыжановский Анатолий.

Slides:



Advertisements
Similar presentations
TechReady 16 4/1/2017 Async Clinic
Advertisements

DEV324 C# VB 7.0 Managed Code C# VB 8.0 Generics C# VB 9.0 Language Integrated Query C# VB 10.0 Dynamic + Language Parity.
Parallel Extensions to the.NET Framework Daniel Moth Microsoft
Exception Handling – illustrated by Java mMIC-SFT November 2003 Anders P. Ravn Aalborg University.
Lightweight Concurrent Tasks Lecture 1.d 6/16/2010 Practical Parallel and Concurrent Programming DRAFT: comments to 1.
Click async Task LoadSettingsAsync() { await IO.Network.DownloadAsync(path); } async void Button1_Click(){ await LoadSettingsAsync(); UpdateView();
Pavel Yosifovich Hi-Tech College
var data = DownloadData(...); ProcessData(data); var future = DownloadDataAsync(...); future.ContinueWith(data => ProcessData(data));
Joe Hummel, PhD Microsoft MVP Visual C++ Technical Staff: Pluralsight, LLC Adjunct Professor: U. of Illinois, Chicago and Loyola University Chicago
Asynchronous programming Deadlock All The Things!.
please wait for the next slide clicking won’t make it come any faster.
Principles Async void is a “fire-and-forget” mechanism… The caller is unable to know when an async void has finished The caller is unable.
DEV415. You are in a dark room with no signs of life. You still have your torch and $356. You can go North (N) or South (S). Your choice? _.
Async Programming WITH ASYNC TASK
Lecture 4 Thread Concepts. Thread Definition A thread is a lightweight process (LWP) which accesses a shared address space provided by by the parent process.
Concurrency Java Threads. Fundamentals Concurrency defines parallel activity Synchronization is necessary in order for parallel activities to share results.
Recognizes: Magic Memo, show me memo number three. Magic Memo, show memo one. Magic Memo, display memo number two. Magic Memo, display memo.
Managed Code Generics Language Integrated Query Dynamic + Language Parity C# VB 11.0 Windows Runtime + Asynchrony C# VB 7.0 C# VB.
Crossword Puzzle Solver Michael Keefe. Solver structure.
PeerFinder.Role = PeerRole.Client; PeerFinder.Role = PeerRole.Host;
Joe Hummel, PhD Technical Staff: Pluralsight Adjunct Professor: UIC, LUC
Образец заголовка Образец текста Второй уровень Третий уровень Четвертый уровень Пятый уровень 1 Investment Attractiveness Index with the support of the.
“Thanks guys for a great information packed day. head is spinning!” “Well done guys. Intense sessions” “This is the best ever JumpStart that I have.
Click async Task LoadSettingsAsync() { await IO.Network.DownloadAsync(path); } async void Button1_Click(){ await LoadSettingsAsync(); UpdateView();
Consuming REST Services from C# SoftUni Team Technical Trainers Software University
Parallel Programming: Responsiveness vs. Performance Joe Hummel, PhD Microsoft MVP Visual C++ Technical Staff: Pluralsight, LLC Professor: U. of Illinois,
public static void PausePrintAsync() { ThreadPool.QueueUserWorkItem(_ => PausePrint()); } public static Task PausePrintAsync() { return Task.Run(()
Lecture 16: Multithreaded Programming. public partial class Form1 : Form { Thread ct; Thread rt; public static int circle_sleep = 0; public static int.
Joe Hummel, PhD Microsoft MVP Visual C++ Technical Staff: Pluralsight, LLC Professor: U. of Illinois, Chicago stuff:
WHO WILL BENEFIT FROM THIS TALK TOPICS WHAT YOU’LL LEAVE WITH ASP.NET developers, including Web Forms & MVC History of async programming in.NET How async.
Command Object’s ExecuteNonQuery Method ISYS 512.
Click async Task LoadSettingsAsync() { await IO.Network.DownloadAsync(path); } async void Button1_Click(){ await LoadSettingsAsync(); UpdateView();
Home reading ‘Five on a Treasure Island’ by Enid Mary Blyton Chapter III. An Exciting Afternoon.

IAsyncResult ar = BeginSomething(…); // Do other work, checking ar.IsCompleted int result = EndSomething(ar);
Problems.Net Анатолий Крыжановский Обра. ООП 2 class Bar { } void Foo(object a) { Console.WriteLine("object"); } void Foo(object a, object b) { Console.WriteLine("object,
Образец заголовка Образец текста Второй уровень Третий уровень Четвертый уровень Пятый уровень 1 Образец заголовка Образец текста Второй уровень Третий.
Asynchronous Programming Writing Asynchronous Code in C# SoftUni Team Technical Trainers Software University
Module 8 Enhancing User Interface Responsiveness.
TAP into async programming
Async Made Simple with C++ PPL
TOPICS WHAT YOU’LL LEAVE WITH WHO WILL BENEFIT FROM THIS TALK.NET library developers : with knowledge of async/await in C# / VB interested in low-level.
Integral Users will interact with your app on a big screen with keyboard and mouse.
App Package Folder App data Folders Local Roaming Temp Removable Storage (SD Card) Cloud Credential Locker B/ground Transfer Publishers Shared Folder.
Print Row Function void PrintRow(float x[ ][4],int i) { int j; for(j=0;j
Chapter 4: Threads Joe McCarthy CSS 430: Operating Systems - Threads1.
task ReadContent(String^ filename) { anim->Start(); auto t = create_task(KnownFolders::DocumentsLibrary-> GetFileAsync(filename)).then( [](StorageFile^
Patterns of Parallel Programming with.NET 4 Stephen Toub Principal Architect Parallel Computing Platform Microsoft Corporation
Int fact (int n) { If (n == 0) return 1; else return n * fact (n – 1); } 5 void main () { Int Sum; : Sum = fact (5); : } Factorial Program Using Recursion.
TOPICS WHAT YOU’LL LEAVE WITH WHO WILL BENEFIT FROM THIS TALK.NET developers: familiar with parallel programming support in Visual Studio 2010 and.NET.
C# 5.0 Alex Davies 22 nd December What we will cover C# 5.0,.NET 4.5, Visual Studio 11 Caller Info Attributes Upgrade from synchronous to asynchronous.
Task and Data Parallelism: Real-World Examples Sasha Goldshtein | SELA Group.
Async Made Simple in Windows 8, with C# and Visual Basic Alex Turner Program Manager VB/C# Compilers Microsoft Corporation DEV332.
Asynchronous Programming Writing Concurrent Code in C# SoftUni Team Technical Trainers Software University
Vaughan Knight App Ecosystem Lead Microsoft FileOpenPicke r, FileSavePicker Read/Write access to SD card Appointments /Calendar API enhancements Appointments.
 Parallel Programming in C# Pro.Net Programming in C#, Adam Freeman.
Asynchronous Programming with C# v.Next
The Future of C# and Visual Basic
TechEd /6/2018 6:15 AM © 2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks.
12 Asynchronous Programming
Asynchronous Programming in .NET
null, true, and false are also reserved.
Asynchronous programming
Build /2/2019 © 2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks.
JavaScript Reserved Words
Web programming and advanced development techniques
Web Service.
03 | Async Programming & Networking Intro
Command Object’s ExecuteNonQuery Method
Poker2.jpg Poker14.jpg int num1, num2;
Presentation transcript:

Образец заголовка Образец текста –Второй уровень Третий уровень –Четвертый уровень »Пятый уровень Тема: Task Parallel Library Крыжановский Анатолий

Образец заголовка Образец текста –Второй уровень Третий уровень –Четвертый уровень »Пятый уровень Одного потока хватит всем?

Образец заголовка Образец текста –Второй уровень Третий уровень –Четвертый уровень »Пятый уровень Варианты многопоточности System.Threading.ThreadSystem.Threading.ThreadPool System.ComponentModel. BackgroundWorker System.Threading.Tasks.Task

Образец заголовка Образец текста –Второй уровень Третий уровень –Четвертый уровень »Пятый уровень Препарируем TPL – создание задачи void SomeWork() { } Task.Run(() => SomeWork()) var task = new Task(() => SomeWork()); task2.Start(); var taskFactory = new TaskFactory(); var task = taskFactory.StartNew(() => SomeWork()); var task = Task.Factory.StartNew(() => SomeWork());

Образец заголовка Образец текста –Второй уровень Третий уровень –Четвертый уровень »Пятый уровень Цепочки задач int SomeWork(int id) { var duration = (int)Math.Round(new Random(id).NextDouble() * 3 + 1); Thread.Sleep(duration * 1000); Console.WriteLine("Work {0} done in {1} seconds", id, duration); return id; } var task = Task.Run (() => SomeWork(1)).ContinueWith(t => Console.WriteLine(t.Result)); var tasks = Enumerable.Range(0, 5).Select(x => Task.Run(() => SomeWork(x))).ToArray(); Task.WhenAll(tasks).ContinueWith(t => Console.WriteLine("all task done")); var tasks = Enumerable.Range(0, 5).Select(x => Task.Run(() => SomeWork(x))).ToArray(); Task.WhenAny(tasks).ContinueWith(t => Console.WriteLine("any task done"));

Образец заголовка Образец текста –Второй уровень Третий уровень –Четвертый уровень »Пятый уровень Тонкая настройка Console.WriteLine("Begin"); var task = new Task(() => { Console.WriteLine("Begin parent task"); var child = new Task(() => { Console.WriteLine("Begin child task"); Thread.Sleep(2000); Console.WriteLine("End child task"); }); child.Start(); Console.WriteLine("End parent task"); }); task.Start(); task.Wait(); Console.WriteLine("End"); Console.WriteLine("Begin"); var task = new Task(() => { Console.WriteLine("Begin parent task"); var child = new Task(() => { Console.WriteLine("Begin child task"); Thread.Sleep(2000); Console.WriteLine("End child task"); }, TaskCreationOptions.AttachedToParent); child.Start(); Console.WriteLine("End parent task"); }); task.Start(); task.Wait(); Console.WriteLine("End"); IsCompletedIsCanceledIsFaulted truefalse NotOnFaulted, NotOnCanceled, OnlyOnRanToCompletion falsetruefalseNotOnRanToCompletion, NotOnFaulted, OnlyOnCanceled false trueNotOnRanToCompletion, NotOnCanceled, OnlyOnFaulted

Образец заголовка Образец текста –Второй уровень Третий уровень –Четвертый уровень »Пятый уровень Подождите, подождите!!! var tasks = Enumerable.Range(0, 5).Select(x => Task.Run(() => SomeWork(x))).ToArray(); Task.WaitAll(tasks); var tasks = Enumerable.Range(0, 5).Select(x => Task.Run(() => SomeWork(x))).ToArray(); Task.WaitAny(tasks, 1); var task = Task.Run(() => SomeWork(0)); task.Wait(); var task = Task.Run(() => SomeWork(0)); var result = task.Result; int SomeWork(int id) { var duration = (int)Math.Round(new Random(id).NextDouble() * 3 + 1); Thread.Sleep(duration * 1000); Console.WriteLine("Work {0} done in {1} seconds", id, duration); return id; }

Образец заголовка Образец текста –Второй уровень Третий уровень –Четвертый уровень »Пятый уровень Отмена задачи void Work() { for (var i = 0; i < 10; i++) { Thread.Sleep(1000); Console.WriteLine("Iteration {0} done", i); } void Work(CancellationToken token) { for (var i = 0; i < 10; i++) { if(token.IsCancellationRequested) return; Thread.Sleep(1000); Console.WriteLine("Iteration {0} done", i); } void Work(CancellationToken token) { for (var i = 0; i < 10; i++) { if(token.IsCancellationRequested) throw new Exception("cancelled"); Thread.Sleep(1000); Console.WriteLine("Iteration {0} done", i); } var task = Task.Run(() => Work()).ContinueWith(t => HandleResult(t)); var cancellationSource = new CancellationTokenSource(); var task = Task.Run(() => Work(cancellationSource.Token), cancellationSource.Token).ContinueWith(t => HandleResult(t)); void Work(CancellationToken token) { for (var i = 0; i < 10; i++) { token.ThrowIfCancellRequested(); Thread.Sleep(1000); Console.WriteLine("Iteration {0} done", i); }

Образец заголовка Образец текста –Второй уровень Третий уровень –Четвертый уровень »Пятый уровень Оживляем UI var task = new Task (() => DoCalculation()); task.ContinueWith(t => ShowResult(t.Result)); task.Start(); var task = new Task (() => DoCalculation()); task.ContinueWith(t => { if(InvokeRequired) Invoke(new Action(() => ShowResult(t.Result))); else ShowResult(t.Result); }); task.Start(); var task = new Task (() => DoCalculation()); task.ContinueWith(t => ShowResult(t.Result), TaskScheduler.FromCurrentSynchronizationContext()); task.Start();

Образец заголовка Образец текста –Второй уровень Третий уровень –Четвертый уровень »Пятый уровень Оживляем UI Task.Factory.StartNew(() => Calc()).ContinueWith((t) => calc.Text = "Go!", TaskScheduler.FromCurrentSynchronizationContext()); private void Calc() { for (int i = 0; i < 10; i++) { Thread.Sleep(1000); var updateUiTask = updateUiTask = Task.Factory.StartNew(() => Update(i), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()); updateUiTask.Wait(); } var context = TaskScheduler.FromCurrentSynchronizationContext(); Task.Factory.StartNew(() => Calc(context)).ContinueWith((t) => calc.Text = "Go!", context); private void Calc(TaskScheduler scheduler) { for (int i = 0; i < 10; i++) { Thread.Sleep(1000); var updateUiTask = Task.Factory.StartNew(() => Update(i), CancellationToken.None, TaskCreationOptions.None, scheduler); updateUiTask.Wait(); }

Образец заголовка Образец текста –Второй уровень Третий уровень –Четвертый уровень »Пятый уровень Плюшки private async void goButton_Click(object sender, EventArgs e) { try { status.Text = "Download data..."; var data = await GetData(url.Text); status.Text = "Processing data..."; var processedData = await DataHandler(data); status.Text = "Done"; result.Text = processedData; } catch (Exception ex) { status.Text = ex.Message; } Task GetData(string url) { return Task.Factory.StartNew(() => { var result = new WebClient().DownloadString(url); return result; }); } Task DataHandler(string data) { return Task.Factory.StartNew(() => { Thread.Sleep(5000); var arr = data.ToCharArray(); Array.Reverse(arr); return new string(arr); }); } var syncContext = TaskScheduler.FromCurrentSynchronizationContext(); status.Text = "Download data..."; var t1 = GetData(url.Text); var t2 = t1.ContinueWith(t => { status.Text = "Processing data..."; return t.Result; }, syncContext); var t3 = t2.ContinueWith(t => { var t4 = DataHandler(t.Result); var t5 = t4.ContinueWith(p => { status.Text = "Done"; result.Text = p.Result; }, syncContext); });

Образец заголовка Образец текста –Второй уровень Третий уровень –Четвертый уровень »Пятый уровень Что почитать?