Event : Visual Studio Users Community Japan #1
Date : 2019/09/14
ソフトウェア/サービス開発において最も後回しにされるものの代表が「パフォーマンスの向上」です。C#/.NET の最大の武器は開発生産性ですが、C# 7.0 以降はパフォーマンス向上のための機能追加が多数行われています。いくつかのポイントを押さえることで実装時からより高速なコードを書くことができるようになります。
このドキュメントでは、そんなポイントとなる箇所をふんだんにお届けします。
Reactive Programming by UniRx for Asynchronous & Event ProcessingYoshifumi Kawai
This document introduces Reactive Programming and UniRx, which is a Reactive Extensions (Rx) library for Unity. It discusses how Rx allows for better event handling and asynchronous programming in Unity by treating events as observable sequences. UniRx brings the benefits of Rx such as LINQ-style querying and orchestration of events and asynchronous operations to Unity. It is available on GitHub and the Unity Asset Store for free.
Clash of Oni Online - VR Multiplay Sword Action Yoshifumi Kawai
"Clash of Oni Online" is made in 2016 Japan VR Hackathon.
2days(31 hours) create vr contents challenge.
This game is made for HTC Vive.
The ancient giant evil Ogre is approaching to the Castle. Charge secret “Samurai Blade” in hand, and repel enemy attack!
Vive Control is your powerful Samurai Blade, hit back rocks Ogre throwing!
Multiplayer online play is available!Cooperate with mate and beat red Ogre up!
A Brief History of UniRx/UniTask, IUniTaskSource in DepthYoshifumi Kawai
The document discusses the architecture of UniTask in C#, including the IUniTaskSource interface and AsyncUniTask class. IUniTaskSource defines methods for getting task results and status and handling completions. AsyncUniTask implements IUniTaskSource and manages a state machine and task pool for asynchronous operations. It retrieves tasks from the pool if available or creates new ones, and returns tasks to the pool after completion.
Deep Dive async/await in Unity with UniTask(EN)Yoshifumi Kawai
The document discusses asynchronous programming in C# using async/await and Rx. It explains that async/await is not truly asynchronous or multithreaded - it is for asynchronous code that runs on a single thread. UniTask is introduced as an alternative to Task that is optimized for Unity's single-threaded environment by avoiding overhead like ExecutionContext and SynchronizationContext. Async/await with UniTask provides better performance than coroutines or Rx observables for Unity.
Memory Management of C# with Unity Native CollectionsYoshifumi Kawai
This document discusses C# and memory management in Unity. It begins by introducing the author and some of their open-source projects related to C# and Unity, including libraries for serialization and reactive programming. It then discusses using async/await with Unity through the UniTask library. The document also covers differences in memory management between .NET Core and Unity due to using different runtimes (CoreCLR vs Unity runtime) and virtual machines. It presents examples of using unsafe code and pointers to directly manage memory in C# for cases like native collections. It concludes that while C# aims for a safe managed world, optimizations require bypassing the runtime through unsafe code, and being aware of memory can help better understand behavior and use APIs more
The document discusses various methods for efficiently serializing and deserializing data in C# using MessagePack, including:
- Methods for reading primitive data types like integers and floats from bytes
- Representing float values as individual bytes for efficient serialization
- Using lookup tables and decoder interfaces to quickly determine MessagePack types and decode values
- Discussing faster alternatives like using direct memory copying instead of serialization delegates
- Mentioning how to extend MessagePack specifications while maintaining compatibility for faster serialization
This document discusses RuntimeUnitTestToolkit, a tool for running unit tests on IL2CPP games. It allows creating unit test classes with public methods that will be automatically registered as tests. Tests can make assertions using the Is method and can be asynchronous by returning IEnumerator. It works with UniRx and allows testing asynchronous coroutines. The tool focuses on play time testing and supports running tests on actual devices.
How to make the Fastest C# Serializer, In the case of ZeroFormatterYoshifumi Kawai
The document discusses ZeroFormatter, an infinitely fast serializer that avoids common serialization inefficiencies. It provides benchmarks showing ZeroFormatter is faster than standard serializers. ZeroFormatter minimizes abstraction by directly writing to byte arrays without boxing or memory streams. Formatter classes handle different types by directly serializing/deserializing values without intermediate serialization steps. This achieves serialization with minimal overhead and memory allocation.
Photon Server Deep Dive - View from Implmentation of PhotonWire, Multiplayer ...Yoshifumi Kawai
This document discusses PhotonWire, a framework for building networked games and applications. It allows clients and servers to communicate asynchronously using operations and operation requests/responses. Clients can send messages to servers using operations, which are received and handled via a switch statement based on operation code. Servers can then send response messages back to clients. The document also mentions plans to improve serialization performance in PhotonWire by replacing the current serializer.
This document discusses using UniRx (Reactive Extensions for Unity) to make asynchronous network requests in a reactive and error-handling manner. Key points include:
1. Wrapping ObservableWWW requests in an ObservableClient to handle errors, timeouts, and retries in a consistent way across methods.
2. Using LINQ operators like Select, Catch, and Timeout to process the network response and handle errors in a reactive pipeline.
3. Implementing more complex retry logic by publishing and connecting an observable to retry requests automatically.
4. Combining multiple asynchronous requests using WhenAll to run them in parallel.
2. @neuecc - Who, Where, When
2009/04
linq.js – LINQ to Objects for JavaScript
https://linqjs.codeplex.com/
この頃からずっとLINQを追いかけてる
2009/09/04
最初のRx記事、以降現在まで70以上は書いてる
http://neue.cc/category/programming/rx/
2011/04~
Microsoft MVP for .NET(C#)
野良C#エヴァンジェリスト(現在も継続中)
25. Same Atmosphere
var query = from person in sequence
where person.Age >= 20
select person.Name;
foreach (var item in query)
{
OnNext(item);
}
var query = from person in sequence
where person.Age >= 20
select person.Name;
query.Subscribe(item =>
{
OnNext(item);
});
IEnumerble<T> IObservable<T>
コレクション処理(filter/map)が超強力で有益なのは既知の話。それと同じように
書ける、同じような挙動を取るということが注意深くデザインされている。
これがRxの革命的なポイントであり普及の一助となった
27. Synchronous Asynchronous
Single(1)Multiple(*)
var x = f(); var x = await f();
var query = from person in sequence
where person.Age >= 20
select person.Name;
foreach (var item in query)
{
OnNext(item);
}
var query = from person in sequence
where person.Age >= 20
select person.Name;
query.Subscribe(item =>
{
OnNext(item);
});
IEnumerble<T> IObservable<T>
Func<T> Task<T>
28. Synchronous Asynchronous
Single(1)Multiple(*)
var x = f(); var x = await f();
var query = from person in sequence
where person.Age >= 20
select person.Name;
foreach (var item in query)
{
OnNext(item);
}
var query = from person in sequence
where person.Age >= 20
select person.Name;
query.Subscribe(item =>
{
OnNext(item);
});
IEnumerble<T> IObservable<T>
Func<T> Task<T>
FutureとかPromise
とか言われるアレの
C#での表現
41. GetStringAsync("http://hogemoge", nextUrl =>
{
GetStringsAsync(nextUrl, finalUrl =>
{
GetStringsAsync(finalUrl, result =>
{
/* result handling */
}, ex => { /* third error handling */ });
}, ex => { /* second error handling */ });
}, ex => { /* first error handling */ });
Callback Hell ネスト地獄による圧倒的
な見通しの悪さ
エラーハンドリングの困難(try-
catchで囲んでも意味が無い)
ObservableWWW.Get("http://hogemoge")
.SelectMany(nextUrl => ObservableWWW.Get(nextUrl))
.SelectMany(finalUrl => ObservableWWW.Get(finalUrl))
.Subscribe(
result => { /*result handling */ },
ex => { /* error handling */ });
ネストを一段に抑える
パイプライン統合のエラー処理
42. Composability
var query = from nextUrl in ObservableWWW.Get("http://hogemoge")
from finalUrl in ObservableWWW.Get(nextUrl)
from result in ObservableWWW.Get(finalUrl)
select new { nextUrl, finalUrl, result };
var parallelQuery = Observable.WhenAll(
ObservableWWW.Get("http//hogehoge"),
ObservableWWW.Get("http//hugahuga"),
ObservableWWW.Get("http//takotako"));
var parallelQuery = Observable.WhenAll(
ObservableWWW.Get("http//hogehoge"),
ObservableWWW.Get("http//hugahuga"),
ObservableWWW.Get("http//takotako"))
.Timeout(TimeSpan.FromSeconds(15));
var incrementalSearch = userInput
.Throttle(TimeSpan.FromMilliseconds(250))
.Select(keyword => SearchAsync(keyword))
.Switch();
前の結果を保持したまま
の直列処理
並べるだけで済む並列処理
メソッドを足すだけのTimeout付与
ユーザー入力など他のIObservableと
の自然な融和と、複雑なPruning
63. 資料紹介
Event processing at all scales with Reactive Extensions
http://channel9.msdn.com/events/TechDays/Techdays-2014-the-
Netherlands/Event-processing-at-all-scales-with-Reactive-Extensions
現時点でのRx入門の決定版といえる素晴らすぃVideo
Bart氏は現在はMicrosoftのPrincipal Software Engineer(偉い)
Cloud-Scale Event Processing Using Rx
http://buildstuff14.sched.org/event/174c265e4ec350bd2e005b59bce0275e
激烈にAdvancedな内容
IReactiveProcessingModel, SubjectのDuality, 次世代のRx(3.0)などなど
更なる未来を見据えた内容なので是非一読を
64. まとめ
LINQ to Everywhere
Reactive Extensions is not only Asynchronous
Reactive Extensions is not only Data-Binding
Observable Everywhere
データソースさえ見つかれば、そこにRxはある
あとは無限の合成可能性を活かせばいい!
まず、データソースを探しだしてください