この問題にはさらに注意を払う必要があり、その解決策はまだ最適化できると感じたので、別のアプローチを投稿することにしました。OP は主に、アプリケーション内のユーザー エクスペリエンス、アプリケーションの内部要件、複数のリクエストによる Web サービスの読み込みという 3 つの範囲の要件を活用することに関する問題です。
- アプリケーションは、データをロードするために最初のリクエストを行う必要があります。
- 彼がそれを要求するとき、ユーザーは最新の更新で結果が得られることを期待しています。
- 一方で、非常に短い時間内に Web サービスへの大規模な一連の呼び出しを開始することはありません。
したがって、この非常に短い時間で何が起こるかを管理することが、実際の問題の解決策になります。
クライアント側では、Service1Client
クラス:
public partial class Service1Client
{
// default time buffer value
int _timeBuffer = 100;
// a time buffer used for returning the same response
public int TimeBuffer
{
get { return _timeBuffer; }
set { _timeBuffer = value; }
}
// the start and end time of the web service request
static DateTime _start, _end;
// a volatile static variable to store the response in the buffering time
volatile static string _response;
// used for blocking other threads until the current thread finishes it's job
object _locker = new object();
public async Task<string> GetResponseData()
{
return await Task.Factory.StartNew<string>(() =>
{
lock (_locker)
{
if (DateTime.Now >= _end.AddMilliseconds(TimeBuffer))
{
_start = DateTime.Now;
var async = GetDataAsync();
_response = async.Result;
_end = DateTime.Now;
}
}
return _response;
});
}
}
テストに使用したコンソール アプリケーション:
class Program
{
static void Main(string[] args)
{
while (true)
{
var client = new ServiceReference1.Service1Client();
client.TimeBuffer = 150;
Console.WriteLine(client.GetResponseData().Result);
if (Console.ReadKey().Key == ConsoleKey.Enter)
break;
}
}
}
注釈として、明確なサンプルの理由から、GetDate
WCF サービスのメソッドの返される型を からDateTime
に変更することにしたことに注意してくださいstring
。
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData();
}
public class Service1 : IService1
{
public string GetData()
{
System.Threading.Thread.Sleep(5000);
return DateTime.Now.ToString();
}
}