More Related Content
Similar to Binary Studio Academy: Concurrency in C# 5.0 (20)
More from Binary Studio (20)
Binary Studio Academy: Concurrency in C# 5.0
- 17. Types Of Threads
● Main Thread (UI Thread)
○ Entry point
○ Sync
● Worker Thread
○ Independent flow
○ Async
- 27. Immutable Collections
● ImmutableStack<T>
● ImmutableQueue<T>
● ImmutableList<T>
● ImmutableSet<T>
● ImmutableDictionary<T, K>
var list = ImmutableList<int>.Empty;
list = list.Insert(0, 1);
list = list.Add(2);
list = list.RemoveAt(0);
Console.WriteLine(list[0]);
- 28. Thread Safe Collections
● ConcurrentStack<T>
● ConcurrentQueue<T>
● ConcurrentBag<T>
ConcurrentDictionary<int, string> dictionary =
new ConcurrentDictionary<int, string>();
dictionary.AddOrUpdate(
k,
key => value,
(key, oldvalue) => value); // if key exist
- 29. Blocking Collections
new BlockingCollection<T>(); // first-in-first-out
new BlockingCollection<T>(new ConcurrentStack<T>()); // last-in-last-out
new BlockingCollection<T>(new ConcurrentBag<T>()); // unordered
Thread1:
_bc.Add(1);
_bc.Add(2);
_blockingQueue.CompleteAdding();
Thread2:
foreach(var item in _bc.GetConsumingEnumerable())
Console.WriteLine(item);
- 33. Asynchronous Programming Model (APM)
● BeginMethod
● Callback
● IAsyncResult
● IAsyncState
● EndMethod
FileStream fs = new FileStream(path, FileMode.OpenOrCreate,
FileAccess.Write, FileShare.None, 8,
FileOptions.Asynchronous);
string content = "A quick brown fox jumps over the lazy dog";
byte[] data = Encoding.Unicode.GetBytes(content);
fs.BeginWrite(data, 0, data.Length, OnWriteCompleted, fs);
private static void OnWriteCompleted(IAsyncResult asyncResult) {
FileStream fs = (FileStream)asyncResult.AsyncState;
fs.EndWrite(asyncResult);
fs.Close();
}
- 34. Event-based Asynchronous Pattern (EAP)
var wc = new WebClient();
wc.DownloadStringCompleted += (sender, args) =>
{
if (args.Cancelled)
Console.WriteLine ("Canceled");
else if (args.Error != null)
Console.WriteLine ("Exception: " +
args.Error.Message);
else
{
Console.WriteLine (args.Result.Length + " chars were
downloaded");
// We could update the UI from here...
}
};
wc.DownloadStringAsync (new Uri ("http://www.linqpad.net")); //
Start it
● Event
● EventArgs
● ObjectState
- 35. Task-based Asynchronous Pattern (TAP)
public Task<T> MethodNameAsync(…, CancellationToken cancellationToken, IProgress<T> progress);
● Task, Task<T>
● CancellationToken
● IProgress
● syntax support (async/await)
- 36. Create task
● new Task(() => return 42).Start()
● TaskFactory.Start(() => return 42)
● Task.Run(() => return 42)
public async Task Method()
{
await Task.Delay(500);
return Task.Run(() => Console.WriteLine(“Async”))
.ContinueWith((t) => Console.WriteLine(“Task finished”));
}
- 38. ConfigureAwait
Public async void Click(object sender, EventArgs args)
{
var str = await service.DownloadString(Url).ConfigureAwait(false);
UxTextBlock.Text = str; // Runtime Error
}
Public async void Click(object sender, EventArgs args)
{
var str = await service.DownloadString(Url);
UxTextBlock.Text = str;
}
- 40. Task Completion Source
public Task UseBackgroundWorker()
{
var tcs = new TaskCompletionSource<double>();
var backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += (o, e) =>
{
Thread.Sleep(2000);
e.Result = 42;
};
backgroundWorker.RunWorkerCompleted += (o, e) =>
{
if (e.Error != null)
{
tcs.SetException(e.Error);
}
else
{
tcs.SetResult((double)e.Result);
}
};
return tcs.Task;
}
- 45. Async lock
SemaphoreSlim _mutex = new SemaphoreSlim(1);
…
public async Task Method()
{
await _mutex.WaitAsync();
try
{
var result =
await httpClient.GetAsync(Url);
}
finally
{
_mutext.Release();
}
}
AsyncLock _mutex = new AsyncLock();
…
public async Task Method()
{
using (await _mutex.LockAsync())
{
var result =
await httpClient.GetAsync(Url);
}
}
Nito.AsyncEx
- 47. Aggregation Exception
Task task1 = Task.Factory.StartNew(() => LongOperationAsync());
try
{
task1.Wait();
}
catch (AggregateException ae)
{
ae.Handle((x) =>
{
if (x is MyException)
{
Console.WriteLine("HandleException.");
return true;
}
return false;
});
}