关于我之前的帖子:910220 - 服务方法独立运行 ,因为代码和我对它的问题的意思有点复杂,我再次带着完全改变的代码来更好地解释自己。
在客户端,我们有:
#define USE_ONLY_ONE_INSTANCE
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using CountTester.ServiceReference1;
namespace CountTester
{
public partial class MainPage : UserControl
{
#if USE_ONLY_ONE_INSTANCE
private readonly Service1Client _sc = new Service1Client();
#endif
public MainPage()
{
InitializeComponent();
#if USE_ONLY_ONE_INSTANCE
_sc.CountCompleted += OnCountCompleted;
#endif
}
void OnCountCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
throw new Exception(string.Format("Count Error {0}", e.Error));
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 100; i++)
{
#if USE_ONLY_ONE_INSTANCE
_sc.CountAsync(i);
#else
var sc = new Service1Client();
sc.CountCompleted += OnCountCompleted;
sc.CountAsync(i);
//sc.CloseAsync();
#endif
}
}
}
}
这是 XAML 背后的代码。在代码中,我调用了一个服务方法 100 次。我尝试了这两种情况并在两种情况下都出现异常: 情况 1:我只使用一个代理实例与服务器进行所有通信。案例 2:我为每次与服务器的通信使用一个实例。
在更多描述之前,让我们看看服务器上的代码:
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Text;
using System.Threading;
namespace CountTester.Web
{
[ServiceContract(Namespace = "")]
[SilverlightFaultBehavior]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1
{
const string logFileName = @"h:\CountTester.log";
object _logLock = new object();
void log(string s)
{
lock (_logLock)
{
var streamWriter = new StreamWriter(logFileName, true, Encoding.ASCII);
streamWriter.Write(s);
streamWriter.Close();
}
}
Service1()
{
//File.Delete(logFileName);
}
[OperationContract]
public void Count(int counter)
{
log(string.Format("{0}\n", counter));
Thread.Sleep(3000);
}
}
}
Count 是被调用的服务方法。我故意在方法中等待 3 秒。我期望的是,客户端的 for 可以毫不拖延地完成。我希望该方法被异步调用,这意味着第一次调用不会影响第二次调用。
换句话说,如果我调用该方法并且它等待完成,再次调用它不会延迟。
虽然是这样。我怎么知道会发生这种情况?通过使用 Tail for Windows,我发现记录的数字在被记录时被延迟。当我看到响应调用服务方法(计数错误...)时出现超时异常时,我也发现了这一点。我希望我能澄清我的问题。
我还想知道当我看到程序出现故障时(异常),当我取消注释我关闭服务的行时?
请回答这两个问题。