2013-01-24 2 views
0

간단한 Silverlight 응용 프로그램을 개발하고 있습니다. 응용 프로그램은 웹 서버의 동일한 시스템에서 실행중인 OPC 서버의 태그에있는 정보를 표시합니다.WCF RIA 서비스에서 OPC 클라이언트의 단일 인스턴스

클라이언트가 태그의 값을 요청하도록하는 방법으로 도메인 서비스 클래스를 구현했습니다. 문제는 클라이언트 측에서 메서드를 호출 할 때마다 새로운 OPC 클라이언트를 인스턴스화하고 서버에 연결하여 값을 읽은 다음 연결을 끊는 것입니다. 이것은 많은 수의 호출에 문제가 될 수 있습니다.

서버 측에서 단일 OPC 클라이언트 개체를 어떻게 사용할 수 있습니까?

다음은 도메인 서비스 클래스의 코드입니다.

namespace BFLabClientSL.Web.Servizi 
{ 
    using System; 
    using System.Collections.Generic; 
    using System.ComponentModel; 
    using System.ComponentModel.DataAnnotations; 
    using System.Linq; 
    using System.ServiceModel.DomainServices.Hosting; 
    using System.ServiceModel.DomainServices.Server; 
    using OpcClientX; 
    using System.Configuration; 

    // TODO: creare metodi contenenti la logica dell'applicazione. 
    [EnableClientAccess()] 
    public class DSCAccessoDati : DomainService 
    { 
     protected OPCItem itemOPC = null; 

     /// <summary> 
     /// Permette l'acceso al valore di un dato 
     /// </summary> 
     /// <param name="itemCode">Chiave del dato</param> 
     /// <returns>Valore del dato</returns> 
     public string GetDato(string itemCode) 
     { 
      string result = ""; 

      OPCServer clientOPC = new OPCServer(); 
      clientOPC.Connect(Properties.Settings.Default.OPCServer_ProgID); 
      OPCGroup gruppoOPC = clientOPC.OPCGroups.Add("Gruppo1"); 

      OPCItem itemOPC = gruppoOPC.OPCItems.AddItem(itemCode, 0); 

      try 
      { 
       object value = null; 
       object quality = null; 
       object timestamp = null; 

       itemOPC.Read(1, out value, out quality, out timestamp); 

       result = (string)value; 
      } 
      catch (Exception e) 
      { 
       throw new Exception("Errore durante Caricamento dato da OPCServer", e); 
      } 
      finally 
      { 
       try 
       { 
        clientOPC.Disconnect(); 
       } 
       catch { } 
       clientOPC = null; 
      } 

      return result; 
     } 
    } 
} 

답변

0

간단한 솔루션은 한 번 초기화하기 클래스에 정적 변수 OPCServer를 정의하고 방법에 재사용하는 것

public class DSCAccessoDati : DomainService 
{ 
    private static OPCServer clientOPC; 

    static DSCAccessoDati() { 
     clientOPC = new OPCServer(); 
     clientOPC.Connect(Properties.Settings.Default.OPCServer_ProgID); 
    } 

    public string GetDato(string itemCode) { 

     OPCGroup gruppoOPC = clientOPC.OPCGroups.Add("Gruppo1"); 
     //your code without the disconnect of OPCServer 
    } 
관련 문제