문제
일시적으로 연결하는 정적 메서드에 정적 이벤트가 있습니다. 메모리에 남아 있거나 두 번 호출하면 두 개의 이벤트 핸들러가 실행되는 상황이 발생하는 것을 원하지 않기 때문입니다.
나는 이것이 정적이어야 하는지 아닌지에 대해 거의 말할 수 없으며 토론/리팩터링 책임을 지지 않는 것을 선호합니다.
처음엔 이렇게 하고 있었는데
public static void DoSomething()
{
try
{
MyStaticClass.MyEvent +=new EventHandler<HandledEventArgs>(MyStaticClass_HandleMe);
... //Doing Stuff
}
finally
{
MyStaticClass.MyEvent -=new EventHandler<HandledEventArgs>(MyStaticClass_HandleMe);//Detach from event
}
}
이것은 잘 작동했지만 이벤트를 인라인으로 처리하고 메서드의 다른 이벤트와 일관성을 유지하고 함수에 로컬이고 다른 이벤트에서 사용되는 취소 부울을 설정하고 싶습니다.
public static void DoSomething()
{
try
{
bool cancel = false;
MyStaticClass.MyEvent +=new EventHandler<HandledEventArgs>(delegate(object sender, HandledEventArgs e)
{
cancel = true;
})
... //Doing Stuff dependent on cancel = false;
}
finally
{
//???
}
}
제 질문은 시나리오 2에서 정적 이벤트를 어떻게 정리하고 분리할 수 있느냐는 것입니다.
해결책
다음과 같이 시도해 볼 수 있습니다.
public static void DoSomething()
{
bool cancel = false;
EventHandler<EventArgs> handler = delegate { cancel = true; };
try
{
MyStaticClass.MyEvent += handler;
}
finally
{
MyStaticClass.MyEvent -= handler;
}
}
다른 팁
기본적으로 인라인 메서드를 대리자에 저장하고 최종적으로 구독을 취소하면 됩니다.
제휴하지 않습니다 StackOverflow