在我的silverlight应用程序中,我将方法GetListCallBack
传递给Repository类中的另一个方法GetEmployees
的委托参数,该参数将该委托作为事件处理程序附加到异步服务调用的完成事件。事件处理程序未取消订阅
EmpViewModel类:
public class EmpViewModel
{
private IRepository EMPRepository = null;
//constructor
public EmpViewModel
{
this.EMPRepository= new Repository();
}
public void GetList()
{
this.EMPRepository.GetEmployees(xyz, this.GetListCallBack);
}
public void GetAnotherList()
{
this.EMPRepository.GetEmployees(pqr, this.GetAnotherListCallBack);
}
private void GetListCallBack(object sender, GetListCompletedEventArgs args)
{
if (args.Error == null)
{
this.collection1.Clear();
this.collection1 = args.Result;
}
else
{
//do sth
}
}
public void GetAnotherListCallback(object sender, GetListCompletedEventArgs args)
{
//do sth with collection1
}
}
仓储类:
public class Repository : IRepository
{
private readonly ServiceClient _client=null ;
public Repository()
{
_client = new ServiceClient(Binding, Endpoint);
}
public void GetEmployees(int xyz, EventHandler<GetListCompletedEventArgs> eventHandler)
{
_client.GetListCompleted -= eventHandler;
_client.GetListCompleted += new EventHandler<GetListCompletedEventArgs>(eventHandler);
_client.GetListAsync(xyz);
}
}
现在,当GetList()
已经完成,然后,如果我调用另一个方法GetAnotherList()
在同一类EmpViewModel
,则该方法的调用在调用GetAnotherListCallBack
之前,再次调用方法GetListCallBack
。
这可能是因为这两种方法都订阅了该事件。
正如你所看到的,我已经明确地从回调事件中取消订阅事件处理器,但仍然调用事件处理器。 任何人都可以请建议我可能会出错的地方吗?
编辑:
当我使用的,而不是使用this.EMPRepository
调用Repository
方法效果很好既是回调方法传递给Repository
类的不同实例,只有attched回调方法被炒鱿鱼
public class EmpViewModel
{
public void GetList()
{
EMPRepository = new Repository();
EMPRepository.GetEmployees(xyz, this.GetListCallBack);
}
public void GetAnotherList()
{
EMPRepository = new Repository();
EMPRepository.GetEmployees(pqr, this.GetAnotherListCallBack);
}
--------
您可以更改“ServiceClient”类的代码吗?它应该是固定的东西。 – 2013-04-10 06:57:21
@ MD.Unicorn ServiceClient类是在添加服务引用时由VS自动生成的。 – Raj 2013-05-07 12:59:47