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();
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
27. async Task<int> FuncAsync() {
int r = await DoAsync();
return r;
}
• TAP과 함께
• 비동기 함수의 이름은
XxxAsync()/XxxTaskAsync()
• async와 await는 함께
• 반환형은 Task, Task<TResult>
Developers love C++ for its compatibility across platforms. Visual Studio 2013 continues to enhance compatibility through language enhancements.
Developer productivity has also improved.
[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.