0
我正在開發一個簡單的Silverlight應用程序。應用程序將顯示在服務器的標籤中找到的信息,這些信息在Web服務器的同一臺機器上運行。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;
}
}
}