125
Puzzles Workshop KATHLEEN DOLLARD - CODERAPID @KATHLEENDOLLARD KATHLEENDOLLARD K [email protected] BLOG: HTTP ://BLOGS.MSMVPS.COM/KATHLEEN HTTP://WWW.PLURALSIGHT.COM/AUTHOR/KATHLEEN- DOLLARD

EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

  • Upload
    hathu

  • View
    235

  • Download
    2

Embed Size (px)

Citation preview

Page 1: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Puzzles Workshop

KATHLEEN DOLLARD - CODERAPID

@KATHLEENDOLLARD

KATHLEENDOLLARD

[email protected]

BLOG: HTTP://BLOGS.MSMVPS.COM/KATHLEEN

HTTP://WWW.PLURALSIGHT.COM/AUTHOR/KATHLEEN -DOLLARD

Page 2: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Puzzles

Page 3: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

EXPLORING THE SURPRISES IN .NET

Page 4: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

COMIC BOOK

GRAPHIC NOVELAPPROACH TO

ASYNC

Page 5: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

http://channel9.msdn.com/Events/BUILD/BUILD2011/SAC-808T

Page 6: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Async and Multi-threading are different

Async Multi-thread

Page 7: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Async and Multi-threading are different

Async Multi-thread

Page 8: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Async and Multi-threading are different

Async

Multi-thread

Multiple operations sharing CPU

Multi-threaded operations are asynchronous

Get Async right, then do multi-threading

Operations overlap with other operations◦ Long file operations, database calls or network requests

Asynchronous operations may not be multi-threaded

Mads Torgersen: “discontinuous sequential” operations

Page 9: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Job TodayBelieve that async doesn’t require threads

Understand how your code is split up on compile

Catch how exceptions pass through async code

Learn about WhenAny and WhenAll combinators

See how threads start with Run

Comprehend cancellation and timeout

Know how to report progress

Look at concurrency issues

Demo debugging

Page 10: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Click

Sub Button1_Click(...)

LoadSettings()

UpdateView()

End Sub

Click

Mes

sage

pu

mp

Thanks Greg Paparin!

Sub LoadSettings()

IO.File.ReadAllText(path)

End Sub

Page 11: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Sub LoadSettings()

IO.Network.Download(path)

End Sub

Sub Button1_Click(...)

LoadSettings()

UpdateView()

End Sub

Mes

sage

pu

mp

Click

Click

Thanks Greg Paparin!

Page 12: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Async Sub Button1_Click(...)

Await LoadSettingsAsync()

UpdateView()

End Sub

Click

Async Function LoadSettingsAsync() As Task

Await IO.Network.DownloadAsync(path)

End Sub

Mes

sage

pu

mp

Task ...DownloadAsync

Task ...LoadSettingsAsync

Download

LoadSettings

Click

Thanks Greg Paparin!

Page 13: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Start

End

© Kathleen Dollard. All rights reserved.

Page 14: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Start

End

© Kathleen Dollard. All rights reserved.

Page 15: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Start

End

© Kathleen Dollard. All rights reserved.

Page 16: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Start

End

© Kathleen Dollard. All rights reserved.

Page 17: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Start

End Task1

Object

© Kathleen Dollard. All rights reserved.

Page 18: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

2012

Start

End Task1

Object

© Kathleen Dollard. All rights reserved.

Page 19: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

19

Your code

NOMTNot on “main” thread

Main Thread

Task Object

Your continuation

Event

Task ObjectTask Object

private async Task<int> LongOp(){ Console.WriteLine("1.In LongOp");await Task.Delay(3000));Console.WriteLine("3.Done!");return 42;

}

Page 20: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

20

Your code

NOMTNot on “main” thread

Main Thread

Task Object

Your continuation

Event

Task Object

private async Task<int> LongOp(){ Console.WriteLine("1.In LongOp");await Task.Delay(3000));Console.WriteLine("3.Done!");return 42;

}

private async Task<int> LongOp(){ Console.WriteLine("1.In LongOp");

await Task.Delay(3000));

Console.WriteLine("3.Done!");return 42;

Page 21: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Logical Code Rewriting

Task Object

private async Task<int> LongOp(){ Console.WriteLine("1.In LongOp");await Task.Delay(3000));Console.WriteLine("3.Done!");return 42;

}

private async Task<int> LongOp(){ Console.WriteLine("1.In LongOp");

await Task.Delay(3000));

Console.WriteLine("3.Done!");return 42;

() => {

}

Page 22: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Code Rewriting with Variable

Task Object

private async Task<int> LongOp(){ Console.WriteLine("1.In LongOp");int val = 3;await Task.Delay(3000));Console.WriteLine(val +" Done!");return 42;

}

private async Task<int> LongOp(){ Console.WriteLine("1.In LongOp");int val = 3;

await Task.Delay(3000));

Console.WriteLine(val + "Done!");return 42;

() => {

}

Page 23: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

23

Your code

System.IO wrapper

NOMTNot on “main” thread

Main Thread

Task Object

Your continuation

Event

System.IO wrapper

Task ObjectTask Object

System.IO wrapper

Page 24: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

24

NOMTNot on “main” thread

Main Thread

Code

System.IO wrapper

Task Object

Continuation

System.IO wrapper

Task ObjectTask Object

System.IO wrapper

Code Continuation

Page 25: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

25

Your code

System.IO wrapper

NOMTNot on “main” thread

Main Thread

Task Object

Your continuation

Event

System.IO wrapper

Task ObjectTask Object

System.IO wrapper

Page 26: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

26

Your code

System.IO wrapper

NOMTNot on “main” thread

Main Thread

Task Object

Your continuation

Task.Run()

Task ObjectTask Object

Task.Run()

Page 27: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Async Exceptions

Page 28: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Your code

System.IO wrapper

NOMTNot on “main” thread

Main Thread

Task Object

Your continuation

catch {

// handle and/or

// rethrowSystem.IO wrapper

Task ObjectTask Object

System.IO wrapper

30

Catch can appear

anywhere in

continuation stack

Page 29: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

WHENALL, WHENANY, RUN, FROMRESULT, DELAY

Combinators

Page 30: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Task.WhenAll◦ Asynchronously await completion of all tasks

Task.WhenAny◦ Asynchronously await one of multiple tasks

Task.Run◦ Run a task using the thread pool

Task.FromResult◦ Immediately return result lifted into a task for task returning method

Task.Delay◦ Non-blocking timer for delays (use instead of Thread.Sleep)

Create your own combinators◦ Which really just means create appropriate helper classes◦ Examples include RetryOnFault and WhenAllOrFirstException

Page 31: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

33

Your code

NOMTNot on “main” thread

Main Thread

Continuation

Task Object

wrapper

Task Object

Task Object

wrapper

wrapper

WhenAll task

Page 32: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

34

Your code

NOMTNot on “main” thread

Main Thread

Continuation

Task…

wrapper

Task Object

Task Object

wrapper

wrapper

Task Object

Task Object

WhenAll task

Page 33: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Task Object

WhenAll task

35

Your code

NOMTNot on “main” thread

Main Thread

Continuation

wrapper

Task Object

wrapper

wrapper

Task Object

wrapper

wrapper

Task Object

Page 34: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

TaskObject

WhenAll task

36

Your code

NOMTNot on “main” thread

Main Thread

Continuation

wrapper

Task Object

wrapper

wrapper

Task Object

wrapperwrapper

Task Object

Page 35: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

When to Use WhenAllTasks to run at the same time

◦ Example: multiple web requests

There is no dependency between tasks◦ One task doesn’t depend on the result of a previous task

◦ If dependencies exist, use sequential async processing

All tasks need to complete, or all results are required, before the continuation occurs

The same exception handling (catch) is needed for all tasks◦ Exceptions appear in the tasks aggregate exception

◦ First exception is also thrown

All of the results are supplied in the resulting array

Page 36: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

WhenAll vs. Sequential Async Operations

Page 37: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

39

Your code

NOMTNot on “main” thread

Main Thread

Task Object

wrapper

Task Object

Continuation

Page 38: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Your code

NOMTNot on “main” thread

Main Thread

Task Object

wrapper

Task Object

Continuation

Task Object

Task Object

40

Page 39: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

NOMTNot on “main” thread

Main Thread

Your code

Task Object

wrapper

Task Object

Continuation

Task Object

Task Object

41

Page 40: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Your code

Task Object

wrapper

Task Object

Continuation

Task Object

Task Object

Task Object

wrapper

Task Object

Continuation

Task Object

Task Object

42

Page 41: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

You only care about one result◦ Redundant operations of which you only need one result

Possibly interleaving (examples on Internet and in my video)◦ You want to work with each result as soon as it is available◦ Consider using TPL for this

Possibly throttling (examples on Internet and in my video)◦ You are using multiple threads and wish to control number used although this is

very rarely needed: Stephen Toub says really, really, really rare◦ If you do need to throttle probably use an alternate task scheduler,

SemaphoreSlim.WaitAsync, or Dataflow and need to read Stephen Toub’s blog

Cancellation◦ Timeout without cancellation token source◦ Early bail with operations that don’t support cancellation

Part of complex scenarios

Page 42: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

WhenAny

Page 43: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

45

Your code

NOMTNot on “main” thread

Main Thread

Continuation

Task Object

wrapper

Task Object

Task Object

wrapper

wrapper

Task Object

Page 44: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

46

Your code

NOMTNot on “main” thread

Main Thread

Continuation

Task…

wrapper

Task Object

Task Object

wrapper

wrapper

Task Object

Task Object

Task Object

Page 45: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Task Object

Task Object

47

Your code

NOMTNot on “main” thread

Main Threadwrapper

Task Object

wrapper

wrapper

Task Object

wrapper

wrapper

Task Object

Continuation

Page 46: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

TaskObject

Task Object

48

Your code

NOMTNot on “main” thread

Main Threadwrapper

Task Object

wrapper

wrapper

Task Object

wrapperwrapper

Task Object

Continuation

Page 47: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

49

Consuming the Task-based Asynchronous Pattern http://bit.ly/WbrfCKNote: There is a second more efficient interleaving pattern far down on that page

Page 48: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Task.Run(action)

Starts a new thread

Static method which returns a Task object

Action can be a lambda expression or a delegateC# will wrap the delegate to a lambda for you

It can also be a Task, allowing async/await within the action

Allows you to explicitly start a task on another thread from the pool

Overloads include parameters that supporting cancellation

If you previously used TPL, this replaces Task.Factory.StartNew()

Page 49: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

51

Your code

Thread from thread pool

Main Thread

Task Object

Your continuation

Task.Run

Page 50: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Sometimes, data is available & can just be returned ◦ Since the method returns a task, we still need one

public Task<int> GetValueAsync(string key){

int cachedValue;return TryGetCachedValue(out cachedValue) ?

Task.FromResult(cachedValue) :GetValueAsyncInternal();

}

private async Task<int> GetValueAsyncInternal(string key){…}

Page 51: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

54

Your code

NOMTNot on “main” thread

Main Thread

Your continuation

Page 52: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Task.DelayAllows non-blocking “wait”

Thread doesn’t sleep

Calling thread is not blocked

Page 53: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

56

Your code

NOMTDoesn’t block main thread

Main Thread

Task Object

Your continuation

Task ObjectTask Object

Page 54: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Cancellation

Page 55: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

62

Your code

NOMTNot on “main” thread

Main Thread

Other code, like button click

Page 56: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Cancellation

Page 57: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

CancellationCancellationTokenSource

◦ Contains CancellationToken

◦ Can initiate cancel

◦ Can link CancellationTokens (logically nesting)

CancellationToken◦ Can be marked “canceled” by TokenSource

◦ Operations can watch and prematurely end

◦ Cannot initiate cancellation

Do not accept cancellation tokens in methods that cannot logically cancel

Page 58: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

65

Your code

NOMTNot on “main” thread

Main Thread

Task Object

Your continuation

Other code, like button click

Page 59: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

66

Your code

Operation wrapper

NOMTNot on “main” thread

Main Thread

Task Object

Your continuation

Other code, like button click

Page 60: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

67

Your code

NOMTNot on “main” thread

Main Thread

Your continuation

Other code, like button click

Exception Catch

Operation wrapper

Task Object

Page 61: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Requires special code

You raise timeout exception

Different times, options

Does not affect other tasks

Does not share token source

Logically differentiated code

Very, very simple

Automatically ends subtasks

◦ If they take CTS

Raises timeout exception

◦ Task is canceled, not faulted

Single timeout for source

Can’t get partial results

Linked sources share CTS

Can register special behavior

WhenAny with Task.Delayrepresenting the timeout

Timeout property on the CancellationTokenSource

Page 62: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

69

Your code

NOMTNot on “main” thread

Main Thread

Task.Delay

Task Object

wrapper

Task Object

Continuation

Task.Delay

Task Object

wrapper

Task Object

Page 63: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

70

Your code

NOMTNot on “main” thread

Main Thread

Continuation

Task.Delay

Task Object

wrapper

Task Object

Task Object

Task Object

Page 64: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

71

Your code

NOMTNot on “main” thread

Main Thread

Continuation

Task…

Task Object

wrapper

Task Object

Task.Delay

Task Object

wrapper

Task Object

Page 65: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

72

Your code

NOMTNot on “main” thread

Main Thread

Task Object

Your continuation

Page 66: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

73

Your code

Operation wrapper

NOMTNot on “main” thread

Main Thread

Task Object

Your continuation

Page 67: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

74

Your code

NOMTNot on “main” thread

Main Thread

Your continuation

Exception Catch

Operation wrapper

Task Object

Page 68: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Progress

Page 69: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Progress TypeSystem.IProgress interface

◦ void Report(T value)

System.Progress<T> class◦ public Progress()

◦ public Progress(Action<T> callback)

◦ public event EventHandler<T> ProgressChanged

◦ protected virtual OnReport method

◦ void IProgress<T>.Report( T value)

Page 70: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

77

Your code

Task.Run

Thread from the thread pool

Main Thread

Task Object

Your continuation

IProgress

Task.Run

Task ObjectTask Object

Task.Run

IProgress.Report

Page 71: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Progress TypesSystem.IProgress interface

◦ void Report(T value)

System.Progress<T> class◦ public Progress()

◦ public Progress(Action<T> callback)

◦ public event EventHandler<T> ProgressChanged

◦ protected virtual OnReport method

◦ void IProgress<T>.Report( T value)

Page 72: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

79

Your code

System.IO wrapper

Thread from the thread pool

Main Thread

Task Object

Your continuation

Progress

Task.Run

Task ObjectTask Object

Task.Run

IProgress.Report

ProgressChanged

event or callback

Page 73: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Logical Context for Async and Multi-threadingClient applications maintain a single UI thread

◦ Important to move blocking tasks like network calls off of this thread

Web servers fill requests with a new thread from the thread pool◦ Creating new threads implicitly or explicitly can lower throughput

◦ Short blocks on the main request thread is sometimes better

Except simple scenarios, plan performance profiling if important

Special considerations for unit testing

© Kathleen Dollard. All rights reserved.

Page 74: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Debugging FeaturesAsync debugging

◦ It just works

Parallel debugging improvements◦ Parallel Watch

◦ Concurrency Visualizer

◦ Flagging threads

◦ Debug Location toolbar

◦ Breakpoint filters

Demo – cool features in a wacky app

Not covering◦ GPU Threads window

Page 75: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Wacky Application to Practice DebuggingThere is a Clip in Module 4 (11C) of my Pluralsight course on multi-threaded debugging.

◦ What’s New in .NET 4.5, Pluralsight, http://bit.ly/100bhzP

To access a similar app and practice debugging, use this help link◦ Topic: “Walkthrough: Debugging a Parallel Application”

◦ Currently at http://bit.ly/VQb926

◦ Will be most useful if you actually do the walk-through

Page 76: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Next Steps

Watch my video ◦ If you don’t have a Pluralsight subscription one month trial, WHAT!?

Use async/await in a test application without multi-threading◦ Probably a UI application

◦ Do NOT do CPU intensive stuff or Thread.Sleep

Create a multi-threaded application for the desktop◦ Get off the main UI thread as much as possible

◦ Play with features like Progress

Create an async application for a server◦ Preserve threads

◦ Consider a web call

Use caution considering multi-threading on server

Page 77: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

LINQ

Page 78: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

LINQ DemosLambdas and Functional Programming

LINQ Queries

Performance

Operators/Methods

Complex Queries

Expressions and Providers

Page 79: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

TracingSOUNDS BORING?

Page 80: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Understanding Production ApplicationsNOT SO BORING?

Page 81: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Things that make debugging hardDesktop

◦ Rare

◦ Distance (can’t sit down and watch)

◦ Watching doesn’t help

◦ Registry corruption/error◦ Machine dependent issues

Server◦ Same issues as desktop plus

◦ Inter-process issues

◦ Higher pressure on threads and memory

◦ Authorization issues

◦ Not being an admin

o Hookup Visual Studio remote debugging?

o Run Visual Studio on your server?

o Buy Ultimate for IntelliTrace?

Page 82: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Two Independent Themes

Abstract your tracing

Appropriate server tracing◦ Out-of-proc

◦ EventSource and ETW, possibly through SLAB

◦ Holistic

Page 83: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Tracing A mechanism for recording the path currently being taken through your application

Page 84: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Your life without tracingYour life with abstracted, semantic, out-of-proc tracing

Page 85: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Abstract!

Page 86: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Abstraction Over Your Logging Framework

Pro

du

ctio

n C

od

e

Sem

anti

c Lo

g A

bst

ract

ion

You

r Lo

ggin

g Fr

amew

ork

Pro

du

ctio

n C

od

e

You

r Lo

ggin

g Fr

amew

ork

System…Trace.Write(...)

Logger.Log.OpenFile(...)

Specific Task

Page 87: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Semantic or Abstract Logging

Strongly typed, IntelliSense driven

Details like keywords and level defined/changed at central point

Aids code readability

Logging framework/tool agnostic

private void FireEvent2_Click(object sender, RoutedEventArgs e){

Logger.Log.Message("Test message");}

private void KeyEvent2_Click(object sender, RoutedEventArgs e){

Logger.Log.AccessByPrimaryKey(GetPrimaryKey(), "Customer");}

Page 88: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Semantic or Abstract LoggingTrace.WriteLine(string.Format(“Access {0} Primary Key {1}”, ”Customer”,42);

Resulting string is not strongly typed◦ Must be read by a human

◦ Or parsed in a fragile manner

Ties logging to technology

Log.AccessByPrimaryKey(“Customer”, 42);

Easier to read intent

Resulting log is strongly typed

Can be used with any logging technology and can shift during project

Page 89: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Tracing records the path through your app

Outside forces affect your app◦ .NET

◦ Operating system

◦ Service/web calls

◦ Many others

o ETW integrates view of your applicationwith outside factors - holistic

Page 90: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Old-Style TracingYou create the entire picture

Tools roughly give you a crayon to draw with

Technique◦ Trace.WriteXxxx

◦ TraceSource

◦ Third-party such as Log4Net

In-process recording devastates scalability

Page 91: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

New-Style Tracingwith EventSource or SLAB

Out-of-proc: Very, very fast because off-thread immediately

Holistic: Vast amount of data already available

Orienteering: Your app drops locations like GPS points

Page 92: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

ETW Sessions – managed by the operating system

ETW Design

ETW

Session

ETW

Session

ETW

Session

ETW SessionETW SessionETW

Controller

ETW SessionETW Session

ETW Provider

ETW SessionETW SessionETW

Consumer

On and off,

filtering

Create

trace entry

Observe,

access

trace info

Page 93: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Controller Consumer

What happens

Page 94: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Black Box Tracing

Asd fdaf fdjkdhfSadfFkjkdslakFddS

Page 95: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Black Box Tracing

Page 96: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Black Box Tracing

Page 97: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Black Box Tracing

Page 98: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

DemoPERFVIEW

Page 99: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

System.Diagnostics…◦ Old stuff

System.Diagnostics.Tracing◦ New stuff (.NET 4.5)

◦ EventSource

◦ EventListener

◦ Microsoft.Diagnostics.Tracing

TraceSource

EventSource

TraceEvent

Class

TraceEvent

Method

TraceListener

EventListener

Naming is Very Confusing

Page 100: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

ETW Design - Processes

ETW Sessions – managed by the operating

systemETW

Session

ETW

Session

ETW

Session

ETW SessionETW SessionETW

Controller

ETW SessionETW SessionETW Provider

ETW SessionETW SessionETW

Consumer

Your App

Page 101: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

ETW Design - Manifests

ETW Sessions – managed by the operating

systemETW

Session

ETW

Session

ETW

Session

ETW SessionETW SessionETW

Controller

ETW SessionETW SessionETW Provider

ETW SessionETW SessionETW

Consumer

Page 102: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

ETW Sessions – managed by the operating

systemETW

Session

ETW

Session

ETW

Session

ETW SessionETW SessionETW

Controller

ETW SessionETW SessionETW Provider

ETW SessionETW SessionETW

Consumer

Binary File

Manifest

ETW Design - Manifests

Page 103: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read
Page 104: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

ETW Design - Manifests

ETW Sessions – managed by the operating

systemETW

Session

ETW

Session

ETW

Session

ETW SessionETW SessionETW

Controller

ETW SessionETW SessionETW Provider

ETW SessionETW SessionETW

Consumer

Binary File

Manifest

Manifest

ProviderId

EventId,

Version

Page 105: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

ETW Sessions – managed by the operating

systemETW

Session

ETW

Session

ETW

Session

ETW SessionETW SessionETW

Controller

ETW SessionETW SessionETW Provider

ETW SessionETW SessionETW

Consumer

Binary File

ManifestManifest

ProviderId

EventId,

Version

ETW

Des

ign

-M

anife

sts

Guid

Integer, small, non-zero

optional

Created from string

via standard algorithm

Page 106: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

ETW Sessions – managed by the operating

systemETW

Session

ETW

Session

ETW

Session

ETW SessionETW SessionETW

Controller

ETW SessionETW SessionETW Provider

ETW SessionETW SessionETW

Consumer

Binary File

Manifest

ETW Design - Manifests

Page 107: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

ETW Sessions – managed by the operating

systemETW

Session

ETW

Session

ETW

Session

ETW SessionETW SessionETW

Controller

ETW SessionETW SessionETW Provider

ETW SessionETW SessionETW

Consumer

Binary File

Manifest

ETW Design - Manifests

Page 108: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

ETW Sessions – managed by the operating

systemETW

Session

ETW

Session

ETW

Session

ETW SessionETW SessionETW

Controller

ETW SessionETW SessionETW Provider

ETW SessionETW SessionETW

Consumer

Binary FileBinary File

Manifest

Manifest

ETW Design - Manifests

Page 109: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

ETW Sessions – managed by the operating

systemETW

Session

ETW

Session

ETW

Session

ETW SessionETW SessionETW

Controller

ETW SessionETW SessionETW Provider

ETW SessionETW SessionETW

Consumer

Binary File

Manifest

ETW Design - Manifests

Page 110: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

ETW Design SummaryETW is composed of

◦ Core (sessions)◦ Controllers◦ Providers◦ Consumers

ETW does most of the work outside your process◦ Particularly important for resources like writing files

ETW is blazingly fast ◦ It’s in the operating system◦ It creates binary files or streams

Manifests explain how to interpret binary files◦ Contain provider IDs (use strings), event IDs (integers 0, 1…), and payload def◦ Can be registered on the machine ◦ Can be in-line in a message

Page 111: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Audiences

ETW Sessions – managed by the operating

systemETW

Session

ETW

Session

ETW

Session

ETW SessionETW SessionETW

Controller

ETW SessionETW SessionETW Provider

ETW SessionETW SessionETW

Consumer

Page 112: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Writing to Channels

.NET 4.5System.Diagnostics.Tracing.

EventSource class

.NET 4.6 or NuGetMicrosoft.Diagnostics.Tracing.

EventSource class

Debug

Analytic

Admin

Operational

Installed Manifest

Supports in-line and

installed manifests

Page 113: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

DemoCREATE SEMANTIC LOGGING

Page 114: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

EventSource StructureSystem.Diagnostics.Tracing.EventSource

Your custom event source class

Static Log property

Method for each event type

Parameter for interesting data

Call to WriteEvent

Page 115: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

EventSource StructureSystem.Diagnostics.Tracing.EventSource

Your custom event source class

Static Log property

Method for each event type

Parameter for interesting data

Call to WriteEvent

Page 116: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Important Attribute ParametersProperty Default Recommended

Name Non-namespacequalified class name

Use a hierarchical name meaningful to the consumer – does not need to contain the class nameDO NOT use the default value

Guid Derived from name and also called the ProviderId

Do not specify but allow to be derived from the name

Property Default

EventId Ordinal from top of classMust match value passed to WriteEvent

Unique identifier for the event

Even

tSo

urc

eEv

ent

Page 117: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Performance SummaryCached Logger int/string Object Overload

Event Off Yes 9ns 100M 20ns 50M

Event Watched Yes 410ns 2M 720ns 1M

Event Off No 9ns 100M 19ns 50M

Event Watched No 410ns 2M 730ns 50M

Integer and string constants same speed

Caching the logger does not alter performance

Object overload is approximately twice as slow

Non-watched events are nearly free

See guidelines in my course (What’s New… & ETW) or blog!

Page 118: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

DemoEXPLORE CODE

PERFVIEW AGAINST RUNNING APP

Page 119: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

SLAB Benefits over direct useFamiliar development experience/familiar listeners (ETW not required)

Really nice documentation

Builds on EventSource, so you get those benefits for free◦ Not even an intervening class

Build/test time tools to validate providers

In process as well of as out of process logging◦ But use out-of-proc

Alternate and multiple listeners

IObservable support

Page 120: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

SummaryETW Architecture

◦ Controllers, consumers, providers

◦ Manifests – installed (NuGet) or in-line

◦ Channels supported in NuGet version

◦ A few tools – WPA in Win 8.1 SDK and PerfView

EventSource◦ .NET 4.5 (also has EventListener which you don’t care much about – use SLAB)

◦ .NET 4.5.1 (validation at build, trace diagnostics-Event Zero/constructor)

◦ NuGet (4.0 support, channels, validation at build, trace diagnostics-Event Zero/constructor, correlation)

Patterns and Practices◦ Semantic Logging Application Block for simple development time listeners

◦ Use only ETW as production listener and controller

Page 121: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

ETW Design SummaryETW is composed of

◦ Core (sessions)◦ Controllers◦ Providers◦ Consumers

ETW does most of the work outside your process◦ Particularly important for resources like writing files

ETW is blazingly fast ◦ It’s in the operating system◦ It creates binary files or streams

Manifests explain how to interpret binary files◦ Contain provider IDs (use strings), event IDs (integers 0, 1…), and payload def◦ Can be registered on the machine ◦ Can be in-line in a message

Page 122: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Please define a few things

Overly Simple (bad) EventSourcenamespace EventDefinitions

{ public class SimpleEventSource : EventSource

{static public SimpleEventSource Log

= new SimpleEventSource();

public void Message(string Message)

{ WriteEvent(1, Message); }

public void AccessByPrimaryKey(

int PrimaryKey, string TableName)

{ WriteEvent(2, PrimaryKey, TableName); }

}

}

Default Id is “SimpleEventSource”

These must match the order of logging methods in the file

Parameters/argsmust match

Page 123: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

“Normal” (good) EventSource

Please define a few things

[EventSource(Name = "KadGen-EtwSamples-Normal")]

public class NormalEventSource : EventSource

{ static public NormalEventSource Log

= new NormalEventSource();

[Event(1)]

public void Message(string Message)

{ WriteEvent(1, Message); }

[Event(2)]

public void AccessByPrimaryKey(int PrimaryKey, string TableName)

{ WriteEvent(2, PrimaryKey, TableName); }

}

Page 124: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

Semantic Logging Application BlockSLABUses EventSource (.NET 4.5+)

◦ No other dependencies

Fantastic documentation, including semantic logging concepts

Out-of-proc provides consumers you’re familiar with

Use in-proc if it’s the best your team can do now

Sadly, lag behind EventSource version

Page 125: EXPLORING THE SURPRISES IN - SDD Conferencesddconf.com/brands/sdd/library/DotNET_Puzzles.pdf · Consider using TPL for this ... SemaphoreSlim.WaitAsync, or Dataflow and need to read

[email protected]

My blog: http://msmvps.com/blogs/kathleen

@kathleendollard on Twitter

www.WintellectNow.com, Free Series

Pluralsight, Kathleen Dollard◦ Event Tracing for Windows (ETW) in .NET, http://bit.ly/1iZeoyZ

◦ .NET Puzzles, http://bit.ly/19z2JaD

◦ What’s New in .NET 4.5, http://bit.ly/YTb962 Module 3 is ETW

◦ Visual Studio 2015 Analyzers, upcoming

Vance Morrison’s blog: http://blogs.msdn.com/b/vancem/

SLAB https://github.com/mspnp/semantic-logging