私の Silverlight アプリケーションでは、Repository クラスGetListCallBackの別のメソッドのデリゲート パラメーターにメソッドを渡して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、GetListCallBack呼び出される前にメソッドが再度GetAnotherListCallBack呼び出されます。
これは、両方のメソッドがイベントにサブスクライブされているため、おそらく発生しています。
ご覧のとおり、イベント ハンドラをコールバック イベントから明示的にサブスクライブ解除しましたが、まだイベント ハンドラが呼び出されています。誰かが私が間違っているかもしれない場所を提案してもらえますか?
編集:
this.EMPRepositoryメソッドを呼び出す代わりにローカル変数を使用すると、Repository両方の CallBack メソッドがRepositoryクラスの異なるインスタンスに渡され、添付された CallBack メソッドのみが起動されるため、うまく機能します
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);
}
--------