Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.ExternalEvaluation/3.3/Drivers/EvaluationServiceClient.cs @ 6470

Last change on this file since 6470 was 6470, checked in by epitzer, 13 years ago

Automatically generate TCPChannel, ProcessChannel and ServiceClient names form parameters (#1526).

File size: 5.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using HeuristicLab.Common;
24using HeuristicLab.Core;
25using HeuristicLab.Data;
26using HeuristicLab.Parameters;
27using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
28
29namespace HeuristicLab.Problems.ExternalEvaluation {
30  [Item("EvaluationServiceClient", "An RPC client that evaluates a solution.")]
31  [StorableClass]
32  public class EvaluationServiceClient : ParameterizedNamedItem, IEvaluationServiceClient {
33
34    public override bool CanChangeName { get { return false; } }
35    public override bool CanChangeDescription { get { return false; } }
36
37    #region Parameters
38    public IValueParameter<IEvaluationChannel> ChannelParameter {
39      get { return (IValueParameter<IEvaluationChannel>)Parameters["Channel"]; }
40    }
41    public IValueParameter<IntValue> RetryParameter {
42      get { return (IValueParameter<IntValue>)Parameters["Retry"]; }
43    }
44
45    private IEvaluationChannel Channel {
46      get { return ChannelParameter.Value; }
47    }
48    #endregion
49
50
51    #region Construction & Cloning
52    [StorableConstructor]
53    protected EvaluationServiceClient(bool deserializing) : base(deserializing) { }
54    protected EvaluationServiceClient(EvaluationServiceClient original, Cloner cloner) : base(original, cloner) {
55      RegisterEvents();
56    }   
57    public EvaluationServiceClient()
58      : base() {
59      Parameters.Add(new ValueParameter<IEvaluationChannel>("Channel", "The channel over which to call the remote function."));
60      Parameters.Add(new ValueParameter<IntValue>("Retry", "How many times the client should retry obtaining a quality in case there is an exception. Note that it immediately aborts when the channel cannot be opened.", new IntValue(10)));
61      RegisterEvents();
62    }
63    public override IDeepCloneable Clone(Cloner cloner) {
64      return new EvaluationServiceClient(this, cloner);
65    }
66    [StorableHook(HookType.AfterDeserialization)]
67    private void AfterDeserialization() {
68      ChannelParameter_ValueChanged(this, EventArgs.Empty);
69      RegisterEvents();
70    }
71    #endregion
72
73    #region IEvaluationServiceClient Members
74    public QualityMessage Evaluate(SolutionMessage solution) {
75      int tries = 0, maxTries = RetryParameter.Value.Value;
76      bool success = false;
77      QualityMessage result = null;
78      while (!success) {
79        try {
80          tries++;
81          CheckAndOpenChannel();
82          Channel.Send(solution);
83          result = (QualityMessage)Channel.Receive(QualityMessage.CreateBuilder());
84          success = true;
85        }
86        catch (InvalidOperationException) {
87          throw;
88        }
89        catch {
90          if (tries >= maxTries)
91            throw;
92        }
93      }
94      return result;
95    }
96
97    public void EvaluateAsync(SolutionMessage solution, Action<QualityMessage> callback) {
98      int tries = 0, maxTries = RetryParameter.Value.Value;
99      bool success = false;
100      while (!success) {
101        try {
102          tries++;
103          CheckAndOpenChannel();
104          Channel.Send(solution);
105          success = true;
106        }
107        catch (InvalidOperationException) {
108          throw;
109        }
110        catch {
111          if (tries >= maxTries)
112            throw;
113        }
114      }
115      System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(ReceiveAsync), callback);
116    }
117    #endregion
118
119    #region Auxiliary Methods
120    private void CheckAndOpenChannel() {
121      if (Channel == null) throw new InvalidOperationException(Name + ": The channel is not defined.");
122      if (!Channel.IsInitialized) {
123        try {
124          Channel.Open();
125        }
126        catch (Exception e) {
127          throw new InvalidOperationException(Name + ": The channel could not be opened.", e);
128        }
129      }
130    }
131
132    private void ReceiveAsync(object callback) {
133      QualityMessage message = null;
134      try {
135        message = (QualityMessage)Channel.Receive(QualityMessage.CreateBuilder());
136      }
137      catch { }
138      ((Action<QualityMessage>)callback).Invoke(message);
139    }
140
141    private void RegisterEvents() {
142      ChannelParameter.ValueChanged += new EventHandler(ChannelParameter_ValueChanged);
143    }
144
145    void ChannelParameter_ValueChanged(object sender, EventArgs e) {
146      if (ChannelParameter.Value == null)
147        name = "Empty EvaluationServiceClient";
148      else
149        name = String.Format("{0} ServiceClient", ChannelParameter.Value.Name);
150      OnNameChanged();
151    }
152    #endregion
153  }
154}
Note: See TracBrowser for help on using the repository browser.