wcf 客户端不稳定问题
在模拟多个客户端访向服务:用多线程以循环方式访问服务,但经常自动退出,出现不稳定情况。 --------------------编程问答-------------------- 不上错误信息你就说不稳定? --------------------编程问答-------------------- 客户端代码:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private delegate void WriteDelegate(string msg);
private void Write(string msg)
{
if (richTextBox1.InvokeRequired)
{
WriteDelegate w = new WriteDelegate(Write);
this.Invoke(w, msg);
}
else
{
richTextBox1.AppendText(msg + "\r\n");
richTextBox1.ScrollToCaret();
}
}
private void btnRun_Click(object sender, EventArgs e)
{
StartThread startThread = new StartThread(this);
startThread.Start();
}
class StartThread
{
private Form1 form;
private Thread myThread;
public StartThread(Form1 form)
{
this.form = form;
myThread = new Thread(Run);
this.myThread.IsBackground = false;
}
public void Start()
{
myThread.Start();
}
void Run()
{
for (int i = 0; i < 1000; i++)
{
MyThread myThread = new MyThread(form, i);
myThread.Start();
}
}
}
class MyThread
{
private int no;
private Form1 form;
private Thread myThread;
public MyThread(Form1 form, int no)
{
this.no = no;
this.form = form;
myThread = new Thread(Run);
this.myThread.IsBackground = false;
}
public void Start()
{
myThread.Start();
}
void Run()
{
for (int i = 0; i < 10000000; i++)
{
double rs = 0;
string str = string.Empty;
ICalculator proxy = null;
try
{
EndpointAddress ea = new EndpointAddress("net.tcp://localhost:9999/CalculatorService");
//proxy = ChannelFactory<ICalculator>.CreateChannel(new NetTcpBinding(), ea);
//ICalculator proxy = DuplexChannelFactory<ICalculator>.CreateChannel(new InstanceContext(new CalculatorCallBack()), new NetTcpBinding(), ea);
//ChannelFactory<ICalculator> channelFactory = new ChannelFactory<ICalculator>(new NetTcpBinding(), ea);
//proxy = channelFactory.CreateChannel();
proxy = DuplexChannelFactory<ICalculator>.CreateChannel(new NetTcpBinding(), ea);
rs = proxy.Add(10, 20, out str);
//Thread.Sleep(3000);
(proxy as ICommunicationObject).Close();
}
catch (TimeoutException)
{
if (proxy != null)
(proxy as ICommunicationObject).Abort();
}
catch (CommunicationException)
{
if (proxy != null)
(proxy as ICommunicationObject).Abort();
}
catch
{
string abc = "";
}
//form.Write(string.Format("{0:d3} :10 + 20 = {1}", no, rs));
form.Write(string.Format("{0} {1:d3} - {2:d10} :10 + 20 = {3}", str, no, i, rs));
}
//form.Write(string.Format("{0:d3} Finished", no));
}
}
}
会出现以下种情況:
1.客戶端自动关闭,VS 无报错;
2.DisconnectedContext was detected(內容 '0x1b6f0760' 已中斷連接。正在從目前的內容 (內容 0x1b6f0510) 釋放介面。這可能會導致損毀或資料遺失。若要避免這個問題,請確認所有內容/Apartment 是否能保持運作,直到應用程式不再使用 RuntimeCallableWrapper 為止 (它代表在這些內容/Apartment 內部運作的 COM 元件) 。)
3.把代码改为单线,也会出现以上情況,.....HELP!!!
第一次使用WCF,还请各位高手指教一下! --------------------编程问答-------------------- 请高手指教!
补充:.NET技术 , Web Services