SlideShare a Scribd company logo
1 of 30
12월의 주제 
C#완벽분석, 원샷 올킬! 
C#을 이용한 Task 병렬화와 비동기 패턴 
-한국마이크로소프트 에반젤리스트 김명신 부장
• 
• 
• 
• 
• DLL Thread attach/detach 
notification 
• Context Switching 
대략 1053KB 남짓 
DLL이 많으면 많을수록, 
스레드가 많으면 많을수록
 우리가 TASK 병렬화를 알아야 하는 이유
Thread pool 
Requests Queue
public static bool QueueUserWorkItem( 
WaitCallback callBack, 
Object state 
) 
for (int i = 0; i < 100; ++i) 
{ 
ThreadPool.QueueUserWorkItem((obj) => 
Console.WriteLine(Thread.CurrentThread.ManagedThreadId)); 
} 
Console.ReadLine();
// QueueUserWorkItem과 유사 동작을 수행하는 코드 패턴 
Action action = new Action(() => 
Console.WriteLine(Thread.CurrentThread.ManagedThreadId)); 
Task t = new Task(action); // #1: Task 객체 생성 후 
t.Start(); // Start() 명시적 호출 
Task.Run(action); // #2: Task.Run을 이용하여 작업 수행 
// 결과 값을 가져오는 Task 객체 생성, Sun() 호출시 예외가 발생한다면 ? 
Task<int> t = new Task<int>(n => Sum((int)n), 100); 
t.Start(); // 명시적 수행 
t.Wait(); // Task 완료 대기 
Console.WriteLine("The Sum is: " + t.Result); // t.Result 결과 획득
private static int Sum(CancellationToken ct, int n) { 
int sum = 0; 
for (; n > 0; n--) { 
// 작업 취소가 요청되면 OperationCanceledException을 
// innerExceptions로 하는 AggregateException 발생 
ct.ThrowIfCancellationRequested(); 
checked { sum += n; } 
} 
return sum; 
} 
static void Main(string[] args) { 
CancellationTokenSource cts = new CancellationTokenSource(); 
Task<Int32> t = Task.Run(() => Sum(cts.Token, 10000000), cts.Token); 
cts.Cancel(); // 작업 취소 
try { 
Console.WriteLine("The sum is: " + t.Result); 
} catch (AggregateException x) { // AggregateException exception handler 
x.Handle(e => e is OperationCanceledException); // Operation… 이면 처리된 것으로 
Console.WriteLine("Sum was canceled"); 
} 
}
// 결과 값을 가져오는 Task 객체 생성, Sun() 호출시 예외가 발생한다면 ? 
Task<int> t = new Task<int>(n => Sum((int)n), 100); 
t.Start(); // 명시적 수행 
t.Wait(); // Task 완료 대기 
Console.WriteLine("The Sum is: " + t.Result); // t.Result 결과 획득 
// t Task가 완료되면 cwt Task를 수행한다. 
Task<Int32> t = Task.Run(() => Sum(CancellationToken.None, 100)); 
Task cwt = t.ContinueWith( 
task => Console.WriteLine("The sum is: " + task.Result));
// TaskContinuationOptions 
// OnlyOnCanceled, OnlyOnFaulted, OnlyOnRantoCompletion, 그외 기타 등등 
CancellationTokenSource cts = new CancellationTokenSource(); 
cts.Cancel(); 
Task<Int32> t = Task.Run(() => Sum(cts.Token, 100), cts.Token); 
t.ContinueWith( // 성공 완료시 
task => Console.WriteLine("The sum is: " + task.Result), 
TaskContinuationOptions.OnlyOnRanToCompletion); 
t.ContinueWith( // 예외 발생시 
task => Console.WriteLine("Sum threw: "+task.Exception.InnerException), 
TaskContinuationOptions.OnlyOnFaulted); 
t.ContinueWith( 
task => Console.WriteLine("Sum was canceled"), 
TaskContinuationOptions.OnlyOnCanceled);
// Parent/Child Task로의 연결, TaskCreationOptions.AttachedToParent 
Task<Int32[]> parent = new Task<Int32[]>(() => 
{ 
var results = new Int32[3]; 
new Task(() => // 차일드로 연결 
results[0] = Sum(10), TaskCreationOptions.AttachedToParent).Start(); 
new Task(() => // 차일드로 연결 
results[1] = Sum(20), TaskCreationOptions.AttachedToParent).Start(); 
new Task(() => // 차일드로 연결 
results[2] = Sum(30), TaskCreationOptions.AttachedToParent).Start(); 
return results; 
}); 
var cwt = parent.ContinueWith( // parent Task가 끝나면 수행할 Task 연결 
parentTask => Array.ForEach(parentTask.Result, Console.WriteLine)); 
parent.Start();
int int int 
int [] 
60초 
30초
public class MyClass 
{ 
public int Read(byte [] buffer, int offset, int count); 
} 
public class MyClass 
{ 
public IAsyncResult BeginRead( 
byte [] buffer, int offset, int count, 
AsyncCallback callback, object state); 
public int EndRead(IAsyncResult asyncResult); 
} 
public class MyClass 
{ 
public void ReadAsync(byte [] buffer, int offset, int count); 
public event ReadCompletedEventHandler ReadCompleted; 
} 
public class MyClass 
{ 
public Task<int> ReadAsync(byte [] buffer, int offset, int count); 
} 
1. Sync 
2. APM 
3. EAP 
4. TAP
private void Button_Click(object sender, RoutedEventArgs e) 
{ 
string url = "http://windowsteamblog.com/windows/b/windowsexperience/atom.aspx"; 
WebClient client = new WebClient(); 
client.DownloadStringCompleted += client_DownloadStringCompleted; 
client.DownloadStringAsync(new Uri(url)); 
} 
void client_DownloadStringCompleted(object sender, 
DownloadStringCompletedEventArgs arg) 
{ 
Debug.WriteLine(arg.Result); 
}
private void Button_Click(object sender, RoutedEventArgs e) 
{ 
string url = "http://windowsteamblog.com/windows/b/windowsexperience/atom.aspx"; 
WebClient client = new WebClient(); 
client.DownloadStringCompleted += 
(s, arg) => Debug.WriteLine(arg.Result); 
client.DownloadStringAsync(new Uri(url)); 
}
private void Button_Click(object sender, RoutedEventArgs e) 
{ 
string url = "http://windowsteamblog.com/windows/b/windowsexperience/atom.aspx"; 
WebClient client = new WebClient(); 
Task<string> t = client.DownloadStringTaskAsync(new Uri(url)); 
t.Wait();// 작업이 완료되때까지 대기 
Debug.WriteLine(t.Result); 
}
private void Button_Click(object sender, RoutedEventArgs e) 
{ 
Task.Run(() => WorkAsync()); 
} 
private void WorkAsync() 
{ 
string url = "http://windowsteamblog.com/windows/b/windowsexperience/atom.aspx"; 
WebClient client = new WebClient(); 
Task<string> t = client.DownloadStringTaskAsync(new Uri(url)); 
t.Wait();// 작업이 완료되때까지 대기 
Debug.WriteLine(t.Result); 
}
private void Button_Click(object sender, RoutedEventArgs e) 
{ 
string url = "http://windowsteamblog.com/windows/b/windowsexperience/atom.aspx"; 
WebClient client = new WebClient(); 
Task<string> t = client.DownloadStringTaskAsync(new Uri(url)); 
t.ContinueWith((prevTask) => Debug.WriteLine(prevTask.Result)); 
}
async Task<int> FuncAsync() { 
int r = await DoAsync(); 
return r; 
} 
• TAP과 함께 
• 비동기 함수의 이름은 
XxxAsync()/XxxTaskAsync() 
• async와 await는 함께 
• 반환형은 Task, Task<TResult>
Click 
async Task LoadSettingsAsync() { 
await IO.Network.DownloadAsync(path); 
} 
async void Button1_Click(){ 
await LoadSettingsAsync(); 
UpdateView(); 
} 
Click 
Message pump 
Task ... 
DownloadAsync 
Task ... 
LoadSettingsAsync 
Download 
LoadSettings
private async void Button_Click(object sender, RoutedEventArgs e) 
{ 
string url = "http://windowsteamblog.com/windows/b/windowsexperience/atom.aspx"; 
WebClient client = new WebClient(); 
string t = await client.DownloadStringTaskAsync(new Uri(url)); 
Debug.WriteLine(t); 
}
C#을 이용한 task 병렬화와 비동기 패턴

More Related Content

What's hot

Web Application Security
Web Application SecurityWeb Application Security
Web Application Security
Abdul Wahid
 
Threat Hunting with Splunk
Threat Hunting with SplunkThreat Hunting with Splunk
Threat Hunting with Splunk
Splunk
 
Enabling Search in your Cassandra Application with DataStax Enterprise
Enabling Search in your Cassandra Application with DataStax EnterpriseEnabling Search in your Cassandra Application with DataStax Enterprise
Enabling Search in your Cassandra Application with DataStax Enterprise
DataStax Academy
 
Debugging PySpark - PyCon US 2018
Debugging PySpark -  PyCon US 2018Debugging PySpark -  PyCon US 2018
Debugging PySpark - PyCon US 2018
Holden Karau
 

What's hot (20)

Spring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing SupportSpring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing Support
 
Streaming SQL with Apache Calcite
Streaming SQL with Apache CalciteStreaming SQL with Apache Calcite
Streaming SQL with Apache Calcite
 
Windows attacks - AT is the new black
Windows attacks - AT is the new blackWindows attacks - AT is the new black
Windows attacks - AT is the new black
 
Web Application Security
Web Application SecurityWeb Application Security
Web Application Security
 
How the Postgres Query Optimizer Works
How the Postgres Query Optimizer WorksHow the Postgres Query Optimizer Works
How the Postgres Query Optimizer Works
 
ClickHouse Features for Advanced Users, by Aleksei Milovidov
ClickHouse Features for Advanced Users, by Aleksei MilovidovClickHouse Features for Advanced Users, by Aleksei Milovidov
ClickHouse Features for Advanced Users, by Aleksei Milovidov
 
Threat Hunting with Splunk
Threat Hunting with SplunkThreat Hunting with Splunk
Threat Hunting with Splunk
 
Sentry - An Introduction
Sentry - An Introduction Sentry - An Introduction
Sentry - An Introduction
 
Enabling Search in your Cassandra Application with DataStax Enterprise
Enabling Search in your Cassandra Application with DataStax EnterpriseEnabling Search in your Cassandra Application with DataStax Enterprise
Enabling Search in your Cassandra Application with DataStax Enterprise
 
Threat Hunting with Splunk
Threat Hunting with SplunkThreat Hunting with Splunk
Threat Hunting with Splunk
 
Managing Postgres with Ansible
Managing Postgres with AnsibleManaging Postgres with Ansible
Managing Postgres with Ansible
 
Spark SQL Catalyst Code Optimization using Function Outlining with Kavana Bha...
Spark SQL Catalyst Code Optimization using Function Outlining with Kavana Bha...Spark SQL Catalyst Code Optimization using Function Outlining with Kavana Bha...
Spark SQL Catalyst Code Optimization using Function Outlining with Kavana Bha...
 
Comando TAR/GZ
Comando TAR/GZComando TAR/GZ
Comando TAR/GZ
 
Web Security
Web SecurityWeb Security
Web Security
 
Vapt life cycle
Vapt life cycleVapt life cycle
Vapt life cycle
 
intrusion detection system (IDS)
intrusion detection system (IDS)intrusion detection system (IDS)
intrusion detection system (IDS)
 
MySQL Monitoring using Prometheus & Grafana
MySQL Monitoring using Prometheus & GrafanaMySQL Monitoring using Prometheus & Grafana
MySQL Monitoring using Prometheus & Grafana
 
Debugging PySpark - PyCon US 2018
Debugging PySpark -  PyCon US 2018Debugging PySpark -  PyCon US 2018
Debugging PySpark - PyCon US 2018
 
Jvm tuning for low latency application & Cassandra
Jvm tuning for low latency application & CassandraJvm tuning for low latency application & Cassandra
Jvm tuning for low latency application & Cassandra
 
The Cyber Threat Intelligence Matrix
The Cyber Threat Intelligence MatrixThe Cyber Threat Intelligence Matrix
The Cyber Threat Intelligence Matrix
 

Similar to C#을 이용한 task 병렬화와 비동기 패턴

Orsiso
OrsisoOrsiso
Orsiso
e27
 

Similar to C#을 이용한 task 병렬화와 비동기 패턴 (20)

[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless
 
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
 
Async Best Practices
Async Best PracticesAsync Best Practices
Async Best Practices
 
Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOS
 
Google App Engine Developer - Day3
Google App Engine Developer - Day3Google App Engine Developer - Day3
Google App Engine Developer - Day3
 
Orsiso
OrsisoOrsiso
Orsiso
 
Алексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhereАлексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhere
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
Thread
ThreadThread
Thread
 
All you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopAll you need to know about the JavaScript event loop
All you need to know about the JavaScript event loop
 
History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NET
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Parallel Processing
Parallel ProcessingParallel Processing
Parallel Processing
 
Asynchronní programování
Asynchronní programováníAsynchronní programování
Asynchronní programování
 
Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#
 
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel ZikmundNDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
 
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
 
Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
Aplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & JetpackAplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & Jetpack
 

More from 명신 김

More from 명신 김 (20)

업무를 빼고 가치를 더하는 클라우드 기술
업무를 빼고 가치를 더하는 클라우드 기술업무를 빼고 가치를 더하는 클라우드 기술
업무를 빼고 가치를 더하는 클라우드 기술
 
[2020 Ignite Seoul]Azure에서 사용할 수 있는 컨테이너/오케스트레이션 기술 살펴보기
[2020 Ignite Seoul]Azure에서 사용할 수 있는 컨테이너/오케스트레이션 기술 살펴보기[2020 Ignite Seoul]Azure에서 사용할 수 있는 컨테이너/오케스트레이션 기술 살펴보기
[2020 Ignite Seoul]Azure에서 사용할 수 있는 컨테이너/오케스트레이션 기술 살펴보기
 
Best of Build Seoul 2019 Keynote
Best of Build Seoul 2019 KeynoteBest of Build Seoul 2019 Keynote
Best of Build Seoul 2019 Keynote
 
Passwordless society
Passwordless societyPasswordless society
Passwordless society
 
DevOps and Azure Devops 소개, 동향, 그리고 기대효과
DevOps and Azure Devops 소개, 동향, 그리고 기대효과DevOps and Azure Devops 소개, 동향, 그리고 기대효과
DevOps and Azure Devops 소개, 동향, 그리고 기대효과
 
Serverless design and adoption
Serverless design and adoptionServerless design and adoption
Serverless design and adoption
 
Durable functions
Durable functionsDurable functions
Durable functions
 
Azure functions v2 announcement
Azure functions v2 announcementAzure functions v2 announcement
Azure functions v2 announcement
 
Azure functions
Azure functionsAzure functions
Azure functions
 
Logic apps
Logic appsLogic apps
Logic apps
 
Serverless
ServerlessServerless
Serverless
 
Azure event grid
Azure event gridAzure event grid
Azure event grid
 
Serverless, Azure Functions, Logic Apps
Serverless, Azure Functions, Logic AppsServerless, Azure Functions, Logic Apps
Serverless, Azure Functions, Logic Apps
 
Microservices architecture
Microservices architectureMicroservices architecture
Microservices architecture
 
Visual studio 2015를 활용한 개발 생산성 및 코드 품질 혁신
Visual studio 2015를 활용한 개발 생산성 및 코드 품질 혁신Visual studio 2015를 활용한 개발 생산성 및 코드 품질 혁신
Visual studio 2015를 활용한 개발 생산성 및 코드 품질 혁신
 
Connect(); 2016 한시간 총정리
Connect(); 2016 한시간 총정리Connect(); 2016 한시간 총정리
Connect(); 2016 한시간 총정리
 
크로스 플랫폼을 품은 오픈 소스 프레임워크 .NET Core
크로스 플랫폼을 품은 오픈 소스 프레임워크 .NET Core크로스 플랫폼을 품은 오픈 소스 프레임워크 .NET Core
크로스 플랫폼을 품은 오픈 소스 프레임워크 .NET Core
 
Coded UI test를 이용한 테스트 자동화
Coded UI test를 이용한 테스트 자동화Coded UI test를 이용한 테스트 자동화
Coded UI test를 이용한 테스트 자동화
 
VS2015 C++ new features
VS2015 C++ new featuresVS2015 C++ new features
VS2015 C++ new features
 
Welcome to the microsoft madness
Welcome to the microsoft madnessWelcome to the microsoft madness
Welcome to the microsoft madness
 

Recently uploaded

Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Kandungan 087776558899
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
MsecMca
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
Epec Engineered Technologies
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
mphochane1998
 
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
HenryBriggs2
 

Recently uploaded (20)

Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
Bridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptxBridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptx
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
 
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxHOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planes
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 

C#을 이용한 task 병렬화와 비동기 패턴

  • 1. 12월의 주제 C#완벽분석, 원샷 올킬! C#을 이용한 Task 병렬화와 비동기 패턴 -한국마이크로소프트 에반젤리스트 김명신 부장
  • 2.
  • 3.
  • 4. • • • • • DLL Thread attach/detach notification • Context Switching 대략 1053KB 남짓 DLL이 많으면 많을수록, 스레드가 많으면 많을수록
  • 5.
  • 6.
  • 7.  우리가 TASK 병렬화를 알아야 하는 이유
  • 8.
  • 9.
  • 11. public static bool QueueUserWorkItem( WaitCallback callBack, Object state ) for (int i = 0; i < 100; ++i) { ThreadPool.QueueUserWorkItem((obj) => Console.WriteLine(Thread.CurrentThread.ManagedThreadId)); } Console.ReadLine();
  • 12. // QueueUserWorkItem과 유사 동작을 수행하는 코드 패턴 Action action = new Action(() => Console.WriteLine(Thread.CurrentThread.ManagedThreadId)); Task t = new Task(action); // #1: Task 객체 생성 후 t.Start(); // Start() 명시적 호출 Task.Run(action); // #2: Task.Run을 이용하여 작업 수행 // 결과 값을 가져오는 Task 객체 생성, Sun() 호출시 예외가 발생한다면 ? Task<int> t = new Task<int>(n => Sum((int)n), 100); t.Start(); // 명시적 수행 t.Wait(); // Task 완료 대기 Console.WriteLine("The Sum is: " + t.Result); // t.Result 결과 획득
  • 13. private static int Sum(CancellationToken ct, int n) { int sum = 0; for (; n > 0; n--) { // 작업 취소가 요청되면 OperationCanceledException을 // innerExceptions로 하는 AggregateException 발생 ct.ThrowIfCancellationRequested(); checked { sum += n; } } return sum; } static void Main(string[] args) { CancellationTokenSource cts = new CancellationTokenSource(); Task<Int32> t = Task.Run(() => Sum(cts.Token, 10000000), cts.Token); cts.Cancel(); // 작업 취소 try { Console.WriteLine("The sum is: " + t.Result); } catch (AggregateException x) { // AggregateException exception handler x.Handle(e => e is OperationCanceledException); // Operation… 이면 처리된 것으로 Console.WriteLine("Sum was canceled"); } }
  • 14. // 결과 값을 가져오는 Task 객체 생성, Sun() 호출시 예외가 발생한다면 ? Task<int> t = new Task<int>(n => Sum((int)n), 100); t.Start(); // 명시적 수행 t.Wait(); // Task 완료 대기 Console.WriteLine("The Sum is: " + t.Result); // t.Result 결과 획득 // t Task가 완료되면 cwt Task를 수행한다. Task<Int32> t = Task.Run(() => Sum(CancellationToken.None, 100)); Task cwt = t.ContinueWith( task => Console.WriteLine("The sum is: " + task.Result));
  • 15. // TaskContinuationOptions // OnlyOnCanceled, OnlyOnFaulted, OnlyOnRantoCompletion, 그외 기타 등등 CancellationTokenSource cts = new CancellationTokenSource(); cts.Cancel(); Task<Int32> t = Task.Run(() => Sum(cts.Token, 100), cts.Token); t.ContinueWith( // 성공 완료시 task => Console.WriteLine("The sum is: " + task.Result), TaskContinuationOptions.OnlyOnRanToCompletion); t.ContinueWith( // 예외 발생시 task => Console.WriteLine("Sum threw: "+task.Exception.InnerException), TaskContinuationOptions.OnlyOnFaulted); t.ContinueWith( task => Console.WriteLine("Sum was canceled"), TaskContinuationOptions.OnlyOnCanceled);
  • 16. // Parent/Child Task로의 연결, TaskCreationOptions.AttachedToParent Task<Int32[]> parent = new Task<Int32[]>(() => { var results = new Int32[3]; new Task(() => // 차일드로 연결 results[0] = Sum(10), TaskCreationOptions.AttachedToParent).Start(); new Task(() => // 차일드로 연결 results[1] = Sum(20), TaskCreationOptions.AttachedToParent).Start(); new Task(() => // 차일드로 연결 results[2] = Sum(30), TaskCreationOptions.AttachedToParent).Start(); return results; }); var cwt = parent.ContinueWith( // parent Task가 끝나면 수행할 Task 연결 parentTask => Array.ForEach(parentTask.Result, Console.WriteLine)); parent.Start();
  • 17. int int int int [] 60초 30초
  • 18.
  • 19.
  • 20.
  • 21. public class MyClass { public int Read(byte [] buffer, int offset, int count); } public class MyClass { public IAsyncResult BeginRead( byte [] buffer, int offset, int count, AsyncCallback callback, object state); public int EndRead(IAsyncResult asyncResult); } public class MyClass { public void ReadAsync(byte [] buffer, int offset, int count); public event ReadCompletedEventHandler ReadCompleted; } public class MyClass { public Task<int> ReadAsync(byte [] buffer, int offset, int count); } 1. Sync 2. APM 3. EAP 4. TAP
  • 22. private void Button_Click(object sender, RoutedEventArgs e) { string url = "http://windowsteamblog.com/windows/b/windowsexperience/atom.aspx"; WebClient client = new WebClient(); client.DownloadStringCompleted += client_DownloadStringCompleted; client.DownloadStringAsync(new Uri(url)); } void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs arg) { Debug.WriteLine(arg.Result); }
  • 23. private void Button_Click(object sender, RoutedEventArgs e) { string url = "http://windowsteamblog.com/windows/b/windowsexperience/atom.aspx"; WebClient client = new WebClient(); client.DownloadStringCompleted += (s, arg) => Debug.WriteLine(arg.Result); client.DownloadStringAsync(new Uri(url)); }
  • 24. private void Button_Click(object sender, RoutedEventArgs e) { string url = "http://windowsteamblog.com/windows/b/windowsexperience/atom.aspx"; WebClient client = new WebClient(); Task<string> t = client.DownloadStringTaskAsync(new Uri(url)); t.Wait();// 작업이 완료되때까지 대기 Debug.WriteLine(t.Result); }
  • 25. private void Button_Click(object sender, RoutedEventArgs e) { Task.Run(() => WorkAsync()); } private void WorkAsync() { string url = "http://windowsteamblog.com/windows/b/windowsexperience/atom.aspx"; WebClient client = new WebClient(); Task<string> t = client.DownloadStringTaskAsync(new Uri(url)); t.Wait();// 작업이 완료되때까지 대기 Debug.WriteLine(t.Result); }
  • 26. private void Button_Click(object sender, RoutedEventArgs e) { string url = "http://windowsteamblog.com/windows/b/windowsexperience/atom.aspx"; WebClient client = new WebClient(); Task<string> t = client.DownloadStringTaskAsync(new Uri(url)); t.ContinueWith((prevTask) => Debug.WriteLine(prevTask.Result)); }
  • 27. async Task<int> FuncAsync() { int r = await DoAsync(); return r; } • TAP과 함께 • 비동기 함수의 이름은 XxxAsync()/XxxTaskAsync() • async와 await는 함께 • 반환형은 Task, Task<TResult>
  • 28. Click async Task LoadSettingsAsync() { await IO.Network.DownloadAsync(path); } async void Button1_Click(){ await LoadSettingsAsync(); UpdateView(); } Click Message pump Task ... DownloadAsync Task ... LoadSettingsAsync Download LoadSettings
  • 29. private async void Button_Click(object sender, RoutedEventArgs e) { string url = "http://windowsteamblog.com/windows/b/windowsexperience/atom.aspx"; WebClient client = new WebClient(); string t = await client.DownloadStringTaskAsync(new Uri(url)); Debug.WriteLine(t); }

Editor's Notes

  1. Developers love C++ for its compatibility across platforms. Visual Studio 2013 continues to enhance compatibility through language enhancements.
  2. Developer productivity has also improved.
  3. [CLICK] * In any UI application, Winforms/WPF/Silverlight/Phone/Win8, the UI thread runs a loop * When a click arrives, it invokes the handler. [CLICK] * When async method hits first await, returns to its caller. [CLICK] * When it hits first await, ... you know the drill [CLICK] * Back to the message-loop. That's why it's responsive, and ready to handle more UI interactions. * Doesn't freeze. [CLICK] * Later on, let's say the network download has finished. * Task gets marked as completed, and if UI thread is free, can resume where it left off. * That's going to be: finish the method [CLICK] * And so the task gets marked as completed, and again the UI thread can resume where it left off. * Okay, that's the mechanism. * Even if you don't follow, that's fine, we'll spell out the practical ramifications.