분류 전체보기 (328)
.NET (111)
S/W tip (35)
etc (63)
DB (34)
HOT item~! (48)
Disign pettens (4)
UX (6)
나의 S/W (2)
개발관련 이슈 (16)
Diary (1)
웹플러스 (1)
calendar
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
tags
archive
link
ColorSwitch 00 01 02
▣  개발환경 자동화에 대한 추천 조합 - 2009. 11. 13. 09:32

보호되어 있는 글입니다. 내용을 보실려면 비밀번호를 입력하세요.


▣  singleton - Disign pettens - 2009. 10. 29. 13:50

public class Singleton
    {
        private static Singleton _Singleton;

 

        private Singleton(){}

 

        public static Singleton GetInstance()       {
            if (_Singleton = null)
                _Singleton = new Singleton();

            return _Singleton;
        }
    }

 

생성자가 private으로 외부에서는 인스턴스를 생성하지 못하게 하였고..static으로 구성된 메서드에서

인스턴스를 생성하여 리턴해주는.. 별 문제 없어보이는 방식이다..

 

위에 소스로 일반적인 방법으로는 문제 없이 잘 돌아간다. 하지만 멀티스레드를 이용하게 될때 문제가 크게 발생하게된다.!!!!!!

GetInstance()메서드가 한번도 실행되지 않은 상태에서.. 두개의 스레드가 동시에 GetInstance()를 호출 하게 된다면..

하나가 아닌 두개의 인스턴스가 생성되어 버리고 말것이다..

 

2개의 인스턴스를 하나의 인스턴스인줄 알고 사방에서 호출하여 데이타를 주고 받는다면... 엄청난 일이 버러지지 않을까...-_-;

 

그래서 멀티스레드를 이용하더라도 이러한 문제가 생기지 않도록 할 수 있는 방법을 알아보기로 하자.!

 

기본적으로 프로그램이 실행되는 순간 인스턴스를 생성!!!

    public class Singleton
    {
        private static Singleton _Singleton = new Singleton();

        private Singleton(){}

        public static Singleton GetInstance()
        {
            return _Singleton;            
        }
    }

 

하지만 위와 같은 방법에도 단점이 있다..

실행되는 순간 바로 인스턴스를 생성하였기 때문에 프로그램을 사용하면서 종료될때까지 한번도 싱글턴으로 이루어진 인스턴스를 호출 하지 않는다면 자원낭비가 될것이다.

 

물론 무조건 한번은 실행하게 되는 클레스라면 위와같이 구현하더라도 상관없다.

 

한가지 방법이 더 있다. 바로 Lock을 걸어 사용중이라면 못들어오게 하는 방법이다.

 

    public class Singleton
    {
        private static Singleton _Singleton;

        private Singleton(){}

        public static Singleton GetInstance()
        {
            lock (_Singleton)
            {
            if (_Singleton == null)
                _Singleton = new Singleton();
            
            return _Singleton;
            }
        }
    }

 

위에 lock로 묶은 부분을 실행할 때에는 _Singleton을 사용하지 못하게 하는 방법이다.

그래서 멀티스레드 방식을 코딩할때에는 lock 키워드를 사용하게 되는 것을 자주 볼 수 있는데...

대신 lock를 걸게되면 시간이 오래 걸린다는 단점이 생긴다. 그래서 lock을 거는 부분을 최소화 시켜주어야 되겠다..

 

public class Singleton
    {
        private static Singleton _Singleton;

        private Singleton(){}

        public static Singleton GetInstance()
        {
            
            if (_Singleton == null)

            {

                   lock (_Singleton)
                  {
                      _Singleton = new Singleton();
                  }

             }
            return _Singleton;
        }
    }

이번엔 _Singleton == null 일 경우에만 lock을 걸어 보았다. 이렇게 되면 맨 처음 인스턴스를 생성할 때에만 lock을 걸어주게 되어

이후 인스턴스를 불러와서 사용하는 경우에는 아무런 속도저하 없이 사용할 수 있을 것이다.


▣  COM INTEROP - .NET/C# - 2009. 10. 13. 16:09

http://blog.naver.com/horsepia/90004035909

COM Interop Part 2: C# Server Tutorial

COM Interop allows COM developers to access managed code as easily as they access other COM objects. This tutorial demonstrates using a C# server with a C++ COM client. It also explains the following activities:

  • How to create the C# server
  • How to create the COM client

The tutorial also briefly demonstrates the marshaling that is automatically applied between managed and unmanaged components.

COM Interop Part 1: C# Client Tutorial shows the fundamentals of using C# to interoperate with COM objects and is a prerequisite for this tutorial. For an overview of both tutorials, see COM Interop Tutorials.

Sample Files

See COM Interop Part 2 Sample to download and build the sample files discussed in this tutorial.

Further Reading

Tutorial

This tutorial demonstrates the following activities to create the C# server:

  • How to use the Guid attribute on interfaces and classes to expose them as COM objects and how to generate a globally unique identifier (GUID) for the Guid attribute.
  • How to use RegAsm to register a .NET Framework program for use by COM clients and create a type library (.tlb file) from a .NET Framework program.

The tutorial also demonstrates the following activities to create the COM client:

  • How to export managed servers and how to use them to create COM objects.
  • How to import the .tlb file, generated by RegAsm, into the COM client and how to use CoCreateInstance to create an instance of a .NET Framework coclass.
    Note   To create a GUID for interfaces and coclasses that you export to COM clients, use the tool Guidgen.exe, shipped as part of Visual Studio. Guidgen allows you to choose the format in which the GUID is expressed so you don't have to retype it. For more information on Guidgen, see the Knowledge Base article Q168318 "XADM: Guidgen.exe Available Only for Intel Platforms." KB articles are available in the MSDN Library and on the Web at http://support.microsoft.com.

Example

This example consists of two files:

  • A C# file, CSharpServer.cs, that creates the CSharpServer.dll file. The .dll is used to create the file CSharpServer.tlb.
  • A C++ file, COMClient.cpp, that creates the executable client, COMClient.exe.

File 1: CSharpServer.cs

// CSharpServer.cs
// compile with: /target:library
// post-build command: regasm CSharpServer.dll /tlb:CSharpServer.tlb

using System;
using System.Runtime.InteropServices;
namespace CSharpServer
{
   // Since the .NET Framework interface and coclass have to behave as 
   // COM objects, we have to give them guids.
   [Guid("DBE0E8C4-1C61-41f3-B6A4-4E2F353D3D05")]
   public interface IManagedInterface
   {
      int PrintHi(string name);
   }

   [Guid("C6659361-1625-4746-931C-36014B146679")]
   public class InterfaceImplementation : IManagedInterface
   {
      public int PrintHi(string name)
      {
         Console.WriteLine("Hello, {0}!", name);
         return 33;
      }
   }
}

File 2: COMClient.cpp

// COMClient.cpp
// Build with "cl COMClient.cpp"
// arguments: friend

#include <windows.h>
#include <stdio.h>

#pragma warning (disable: 4278)

// To use managed-code servers like the C# server, 
// we have to import the common language runtime:
#import <mscorlib.tlb> raw_interfaces_only

// For simplicity, we ignore the server namespace and use named guids:
#if defined (USINGPROJECTSYSTEM)
#import "..\RegisterCSharpServerAndExportTLB\CSharpServer.tlb" no_namespace named_guids
#else  // Compiling from the command line, all files in the same directory
#import "CSharpServer.tlb" no_namespace named_guids
#endif
int main(int argc, char* argv[])
{
   IManagedInterface *cpi = NULL;
   int retval = 1;

   // Initialize COM and create an instance of the InterfaceImplementation class:
   CoInitialize(NULL);
   HRESULT hr = CoCreateInstance(CLSID_InterfaceImplementation,
               NULL, CLSCTX_INPROC_SERVER,
               IID_IManagedInterface, reinterpret_cast<void**>(&cpi));

   if (FAILED(hr))
   {
      printf("Couldn't create the instance!... 0x%x\n", hr);
   }
   else
   {
      if (argc > 1)
      {
         printf("Calling function.\n");
         fflush(stdout);
         // The variable cpi now holds an interface pointer 
         // to the managed interface.
         // If you are on an OS that uses ASCII characters at the 
         // command prompt, notice that the ASCII characters are 
         // automatically marshaled to Unicode for the C# code.
         if (cpi->PrintHi(argv[1]) == 33)
            retval = 0;
         printf("Returned from function.\n");
      }
      else
         printf ("Usage:  COMClient <name>\n");
      cpi->Release();
      cpi = NULL;
   }

   // Be a good citizen and clean up COM:
   CoUninitialize();
   return retval;
}

Output

The executable client can be invoked with the command line: COMClient <name>, where <name> is any string you want to use, for example, COMClient friend.

Calling function.
Hello, friend!
Returned from function.

In the sample IDE project, set the Command Line Arguments property in the project's Property Pages to the desired string (for example, "friend").



articles
recent replies
recent trackbacks
notice
Admin : New post