C# WCF服务服务器引发异常,无法访问已释放的对象
因此,我的服务是两个wcf客户端之间的简单聊天应用程序。事件回调在我调用事件时起作用。在我关闭客户端并再次运行它,并再次编写消息(调用事件)后,它会向我抛出异常:C# WCF服务服务器引发异常,无法访问已释放的对象,c#,wcf,events,service,delegates,C#,Wcf,Events,Service,Delegates,因此,我的服务是两个wcf客户端之间的简单聊天应用程序。事件回调在我调用事件时起作用。在我关闭客户端并再次运行它,并再次编写消息(调用事件)后,它会向我抛出异常: An exception of type 'System.ObjectDisposedException' occurred in RussianRouletteServiceLibrary.dll but was not handled in user code Additional information: Cannot acc
An exception of type 'System.ObjectDisposedException' occurred in
RussianRouletteServiceLibrary.dll but was not handled in user code
Additional information: Cannot access a disposed object.
我的服务回调的代码如下所示:
private static Action<User, UMessage> gameChat = delegate { };
public void Play()
{
IGameCallback subscriber =
OperationContext.Current.GetCallbackChannel<IGameCallback>();
gameChat += subscriber.PlayerSentMessage;
}
每次我.ChannelFactory.Close()时都会出现此错误代码>.Close()代码>正在发生关闭表单事件时客户端
有没有人知道如何解决这个问题并愿意分享他的知识?
提前谢谢你
编辑#1
这是客户端打开时的代码:
ConcurrencyMode.Multiple,
UseSynchronizationContext = false)]
public partial class GameForm : Form, IGameCallback
{
#region IGame Callbacks
public void PlayerSentMessage(User user, UMessage message)
{
string nickname = user.NickName == clientUser.NickName ? "You" : user.NickName;
this.Invoke(new MethodInvoker(() => lb_ChatBox.Items.Add(nickname + " : " + message.MessageContent)));
}
#endregion
private GameClient _gameClient = null;
private InstanceContext _instance = null;
private User clientUser = new User(){ Email = "zigm4s@gmail.com", Id = 0, FirstName = "Zigmas", LastName = "Slusnys", NickName = "Ziggy", Password = "test123"};
public GameForm()
{
string state;
if (_gameClient != null)
{
MessageBox.Show("nelygu null");
MessageBox.Show(_gameClient.State.ToString());
//_gameClient = new GameClient(new InstanceContext(this));
}
else
{
_gameClient = new GameClient(new InstanceContext(this));
MessageBox.Show(_gameClient.State.ToString());
}
InitializeComponent();
try
{
_gameClient.Open();
_gameClient.Play();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
此时客户端窗体将关闭
private void GameForm_FormClosing(object sender, FormClosingEventArgs e)
{
try {
if (_gameClient.State != System.ServiceModel.CommunicationState.Faulted)
{
MessageBox.Show("Closing client");
_gameClient.ChannelFactory.Close();
_gameClient.Close();
}
else
{
MessageBox.Show("Aborting client");
_gameClient.Abort();
}
}
catch(Exception ex)
{ MessageBox.Show(ex.ToString());}
}
编辑#2
我发现了错误,在服务端,我的代理是静态的。如果不是静态的,它不会抛出此错误。能否显示有关如何关闭客户端然后创建新客户端的更多代码?我添加了客户端打开和关闭,您认为我关闭客户端的方式有问题吗?
private void GameForm_FormClosing(object sender, FormClosingEventArgs e)
{
try {
if (_gameClient.State != System.ServiceModel.CommunicationState.Faulted)
{
MessageBox.Show("Closing client");
_gameClient.ChannelFactory.Close();
_gameClient.Close();
}
else
{
MessageBox.Show("Aborting client");
_gameClient.Abort();
}
}
catch(Exception ex)
{ MessageBox.Show(ex.ToString());}
}