2017년 6월 20일 화요일

[Links] Unit Testing asynchronous code

좀 옛날 글이긴 하지만
VisualStudio에서 MSTest로 unit test case를 작성할 때
Asynchronous code에 대해서 고려해야할 사항을 상세 하게 정리한 글이다.

Async Programming : Unit Testing Asynchronous Code
: https://msdn.microsoft.com/ko-kr/magazine/dn818493.aspx

Async Programming : Unit Testing Asynchronous Code: Three Solutions for Better Tests
: https://msdn.microsoft.com/ko-kr/magazine/dn818494.aspx


사실 요즘 VS에서 MSTest로 async method에 대해서 unit test case를 작성하려면
단순히 public async Task XXXX() prototype으로만 작성하면
test framework에서 Task가 끝날 때 까지 기다리므로 문제는 없다.

하지만 asychronous 하게 testing을 하기 위해서
어떤 방법들을 사용할 수 있는지에 대해서 한번쯤은 봐두면 좋은것 같아
기억 차원에서 링크만 정리함.

이책 한번 도서관에 신청해서 봐야 겠음.
https://www.amazon.com/Concurrency-Cookbook-Asynchronous-Multithreaded-Programming/dp/1449367569/ref=sr_1_1?ie=UTF8&qid=1496741393&sr=8-1&keywords=Concurrency+in+C%23+Cookbook

이책도
http://www.yes24.com/24/goods/25466870?scode=032&OzSrank=1

2017년 6월 1일 목요일

C# struct, value type, reference type

C++에서는 Class와 Struct가 거의 차이가 없어
method가 필요없는 data model은 struct로 지정해서 사용하던게 버릇이었는데
C#에서는 좀 상황이 달라서 찾아봄.

일단 C#에서의 Struct와 Class의 차이점은 아래 정리하였음.
http://charlie0301.blogspot.kr/2016/11/struct-vs-class-in-c.html

간단히 정리하면
https://msdn.microsoft.com/ko-kr/library/aa664471(v=vs.71).aspx

구조체는 여러 가지 중요한 점에서 클래스와 다릅니다.
  • 구조체는 값 형식입니다(11.3.1 단원).
  • 모든 구조체 형식은 암시적으로 클래스 System.ValueType에서 상속됩니다(11.3.2 단원).
  • 구조체 형식의 변수에 대입이 이루어지면 지정되는 값이 복사됩니다(11.3.3 단원).
  • 구조체의 기본값은 모든 값 형식 필드를 기본값으로 설정하고 모든 참조 필드를 null로 설정했을 때 생성되는 값입니다(11.3.4 단원).
  • Boxing과 unboxing 연산은 구조체 형식과 object 간의 변환에 필요합니다(11.3.5 단원).
  • this의 의미는 구조체의 경우 다릅니다(11.3.6 단원).
  • 구조체에 대한 인스턴스 필드 선언은 변수 이니셜라이저를 포함할 수 없습니다(11.3.7 단원).
  • 구조체는 매개 변수가 없는 인스턴스 생성자를 선언할 수 없습니다(11.3.8 단원).
  • 구조체는 소멸자를 선언할 수 없습니다(11.3.9 단원).


요약 첫줄에도 나오듯이 구조체는 value type이라서
구조체 변수간 대입 시 변수의 값을 전달하게 된다는것이 중요.

그럼 자연스레 드는 궁금증은 call by reference, call by value일 것 같은데..
아래 링크를 정독하면 아주 도움이 된다.

http://www.yoda.arachsys.com/csharp/parameters.html

모든 상황에서 다 맞는 것은 아니지만 ...

변수간 대입은 value type이면 value를
reference type이면 reference를...

함수 parameter일 경우
기본적으로 call by value인데
value type의 value는 value, reference type의 value는 reference를 (왠지 말장난같은..)

정도로 요약하여 생각하면 되지 않을까 생각하지만

case마다 딱 들어맞지 않아 한번 정독이 꼭 필요함!!!


2017년 5월 31일 수요일

[Links] 초기화 지연(Lazy Initialization)

Object initiation 같은 부분은 안전빵으로 static으로 선언해서 사용하는 편이라.. 초기화 시점에서의 overhead와 memory footprint가 좀 걱정이 되었는데 좀 사용해 봐야 겠음.

Lazy Initialization

https://msdn.microsoft.com/ko-kr/library/dd997286(v=vs.110).aspx

형식설명
Lazy<T>클래스 라이브러리 또는 사용자 정의 형식을 위한 초기화 지연 의미 체계를 제공하는 래퍼 클래스
ThreadLocal<T>스레드 로컬 방식으로 초기화 지연 의미 체계를 제공한다는 점을 제외하면 Lazy<T>와 비슷합니다. 모든 스레드에서 자체의 고유한 값에 액세스할 수 있습니다.
LazyInitializer클래스 오버헤드 없는 개체의 초기화 지연을 위한 고급 static(Visual Basic의 경우 Shared) 메서드를 제공합니다.
사용시점에 초기화 됨.

            // Initialize by using default Lazy<T> constructor. The 
            // Orders array itself is not created yet.
            Lazy<Orders> _orders = new Lazy<Orders>();

https://msdn.microsoft.com/en-us/library/dd460709(v=vs.110).aspx


  static bool someCondition = false;    
  //Initializing a value with a big computation, computed in parallel  
  Lazy<int> _data = new Lazy<int>(delegate  
  {  
      return ParallelEnumerable.Range(0, 1000).  
          Select(i => Compute(i)).Aggregate((x,y) => x + y);  
  }, LazyExecutionMode.EnsureSingleThreadSafeExecution);  
  
  // Do some work that may or may not set someCondition to true.  
  //  ...  
  // Initialize the data only if necessary  
  if (someCondition)  
{  
    if (_data.Value > 100)  
      {  
          Console.WriteLine("Good data");  
      }  
}  


이런것도 가능하구나...

                    //Initializing a value per thread, per instance
                     ThreadLocal<int[][]> _scratchArrays = 
                         new ThreadLocal<int[][]>(InitializeArrays);
                    // . . .
                     static int[][] InitializeArrays () {return new int[][]}
                    //   . . .
                    // use the thread-local data
                    int i = 8;
                    int [] tempArr = _scratchArrays.Value[i];

간단한 예제와 실제 디버깅.

http://www.c-sharpcorner.com/UploadFile/dacca2/implement-lazy-loading-in-C-Sharp-using-lazyt-class/


2017년 3월 29일 수요일

C# 코딩의 기술 기본편 : 똑똑하게 코딩하는 법
가와마타 아키라 저/김완섭 역 | 길벗

http://m.yes24.com/Goods/Detail/20312268

C#을 쓰기 시작해서 책들을 찾아서 보고 있음.
좀 간단하게 볼만 한 책 중에서는 이 책이 있었음.

두권으로 구성되어 있고 그 중 실전편은 난 별로였으나 기본편은 C# 초보자에게는 간단하게 읽어 볼만 한 것 같다.

저자가 일본 사람이라서 그런지 꼼꼼하게 챕터가 정해진 것 같고 사소하지만 놓치기 쉬운 부분도 함께 정리한 듯 하다. 하지만 책이 대화로 구성되어서 난 보기 쉽지 않더라..

챕터 중 몰랐거나 볼만한 것들은 다음과 같고 나중을 위해 정리해둠.


1.6 루프할 필요가 없는 루프
1.8 해제되지 않는 참조
1.9 해제했다고 생각한 메모리
1.18 using문을 사용하지 않는 증후군

2.1 구세대 컬렉션 사용
2.9 XElement를 Nullable〈T〉로 변환할 수 있을 때
2.13 자바여 편히 잠들라

3.1 GAC에 얽힌 오해
3.2 Ngen 의존 증후군

2017년 3월 27일 월요일

[Link] Xamarin MessagingCenter, publish/subscribe 기반으로 coupling 간단한 message 전달 방법

View model과 다른 component간에 message를 사용하여 연동될 수 있도록 하는 방법이고 message에 대해서 subscribe, publish 하여 사용하므로 coupling을 줄일 수 있다.


: https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/messaging-center/
 

Simple String Message

The simplest message contains just a string in the message parameter. A Subscribe method that listens for a simple string message is shown below - notice the generic type specifying the sender is expected to be of type MainPage. Any classes in the solution can subscribe to the message using this syntax:
MessagingCenter.Subscribe<MainPage> (this, "Hi", (sender) => {
    // do something whenever the "Hi" message is sent
});
In the MainPage class the following code sends the message. The this parameter is an instance of MainPage.
MessagingCenter.Send<MainPage> (this, "Hi");
The string doesn't change - it indicates the message type and is used for determining which subscribers to notify. This sort of message is used to indicate that some event occurred, such as "upload completed", where no further information is required.

하지만 뭐든지 남용하는 건 안될 것 같다.
다음은 MessagingCenter를 사용하지 않아도 될 부분들을 정리해 놓은 내용이다.

Misuses Of MessagingCenter
: https://xamarinhelp.com/common-misuse-messagingcenter/

2017년 3월 8일 수요일