2011-09-11 3 views
1

ive 프로그램에서 작업 중입니다. 나는 3 개의 클래스가 있습니다. 클래스 중 2 개는 서로 다른 간격으로 반복되는 타이머를 가지고 있으며 타이머의 "순환"이 완료되면 문자열을 반환하는 이벤트를 발생시킵니다. 세 번째 클래스는 다른 두 타이머 클래스의 이벤트를 구독하고 화면에 출력합니다. 그것은 위대한 작품!C#에서 이벤트 발생 및 출력?

하지만 내 문제는 개별적으로 인쇄한다는 것입니다. 현재 첫 번째 타이머 클래스가 실행되고 2 분마다 "hello"가 발생하고 매 초 다른 클래스 "dog"가 발생한다고 가정 해보십시오. 이벤트가 발생할 때마다 발생한 이벤트를 콘솔에 출력합니다. 나는 매초마다 "hellodog"를 인쇄하고 싶습니다.

나는 생각했다. 타이머가 작동 할 때마다 이벤트가 발생하고 "출력"클래스의 문자열을 현재 값으로 업데이트 한 다음 매초마다 다른 타이머를 만들고이 타이머는 "hellodog"와 같은 하나의 출력으로 문자열을 업데이트했습니다. 이게 내가 생각하는 가장 쉬운 방법이라면 가능하다. 어떻게이 아이디어를 얻을 수 있을까요?

혼란 스러울 경우 명확히 할 것입니다.

namespace Final 
{ 
    public class Output 
    { 
     public static void Main() 
     { 
      var timer1 = new FormWithTimer(); 
      var timer2 = new FormWithTimer2(); 

      timer1.NewStringAvailable += new EventHandler<BaseClassThatCanRaiseEvent.StringEventArgs>(timer1_NewStringAvailable); 

      timer2.NewStringAvailable += new EventHandler<BaseClassThatCanRaiseEvent.StringEventArgs>(timer2_NewStringAvailable); 
      Console.ReadLine(); 
     } 

     static void timer1_NewStringAvailable(object sender, BaseClassThatCanRaiseEvent.StringEventArgs e) 
     { 
      var theString = e.Value; 

      //To something with 'theString' that came from timer 1 
      Console.WriteLine(theString); 
     } 

     static void timer2_NewStringAvailable(object sender, BaseClassThatCanRaiseEvent.StringEventArgs e) 
     { 
      var theString2 = e.Value; 

      //To something with 'theString2' that came from timer 2 
      Console.WriteLine(theString2); 
     } 
    } 

    public abstract class BaseClassThatCanRaiseEvent 
    { 
     public class StringEventArgs : EventArgs 
     { 
      public StringEventArgs(string value) 
      { 
       Value = value; 
      } 

      public string Value { get; private set; } 
     } 

     //The event itself that people can subscribe to 
     public event EventHandler<StringEventArgs> NewStringAvailable; 

     protected void RaiseEvent(string value) 
     { 
      var e = NewStringAvailable; 
      if (e != null) 
       e(this, new StringEventArgs(value)); 
     } 
    } 

    public partial class FormWithTimer : BaseClassThatCanRaiseEvent 
    { 
     Timer timer = new Timer(); 

     public FormWithTimer() 
     { 
      timer = new System.Timers.Timer(200000); 

      timer.Elapsed += new ElapsedEventHandler(timer_Tick); // Everytime timer ticks, timer_Tick will be called 
      timer.Interval = (200000);    // Timer will tick evert 10 seconds 
      timer.Enabled = true;      // Enable the timer 
      timer.Start();        // Start the timer 
     } 

     void timer_Tick(object sender, EventArgs e) 
     { 
      ... 
      RaiseEvent(gml.ToString());      
     } 
    } 


    public partial class FormWithTimer2 : BaseClassThatCanRaiseEvent 
    { 
     Timer timer = new Timer(); 

     public FormWithTimer2() 
     { 
      timer = new System.Timers.Timer(1000); 

      timer.Elapsed += new ElapsedEventHandler(timer_Tick2); // Everytime timer ticks, timer_Tick will be called 
      timer.Interval = (1000);    // Timer will tick evert 10 seconds 
      timer.Enabled = true;      // Enable the timer 
      timer.Start();        // Start the timer 
     } 

     void timer_Tick2(object sender, EventArgs e) 
     { 
      ... 
      RaiseEvent(aida.ToString()); 
     } 
    } 
} 
+3

가능한 중복 http://stackoverflow.com/questions/7375452/how-do -i-subscribe-to-raised-events-and-printing-together) –

+0

또한 http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be-removed를 참조하십시오. -from-posts –

+0

나는 이해합니다 – Csharpz

답변

1

두 타이머 모두 동일한 이벤트 처리기를 사용할 수 있습니다. 그리고 보낸 사람을 식별하여 출력을 구성합니다. (구문 오류에 대한 코드를 테스트하지 않았나요.)

private static string timer1Value = string.Empty; 
private static string timer2Value = string.Empty; 
private static FormWithTimer timer1; 
private static FormWithTimer2 timer2; 

public static void Main() 
{ 
    timer1 = new FormWithTimer(); 
    timer2 = new FormWithTimer2(); 

    timer1.NewStringAvailable += new EventHandler<BaseClassThatCanRaiseEvent.StringEventArgs>(timer1_NewStringAvailable); 

    timer2.NewStringAvailable += new EventHandler<BaseClassThatCanRaiseEvent.StringEventArgs>(timer1_NewStringAvailable); 
    Console.ReadLine(); 
} 


static void timer1_NewStringAvailable(object sender, BaseClassThatCanRaiseEvent.StringEventArgs e) 
{ 
    if (sender == timer1) 
    { 
     timer1Value = e.Value.ToString(); 
    } 
    else if (sender == timer2) 
    { 
     timer2Value = e.Value.ToString(); 
    } 

    if (timer1Value != String.Empty && timer2Value != String.Empty) 
    { 
     Console.WriteLine(timer1Value + timer2Value); 
     // Do the string concatenation as you want. 
    } 
[I가 함께 발생한 이벤트 및 인쇄에 가입하려면 어떻게합니까?] (의
+0

면 (보낸 사람 == FormWithTimer) 내가 오류가 변수로 사용되는 형식입니다. 하지만 어쩌면 그것을 고칠 수 있습니다. 어떤 팁? – Csharpz

+1

죄송합니다 보낸 사람 == timer1 및 보낸 사람 == timer2 – CharithJ

+0

ahh 고마워,하지만 지금은 개체 참조를 얻으려면 비 정적 메서드 또는 필드 Output.timer1 필요합니다. – Csharpz

1

이벤트가 예제에서 처리되면 다른 이벤트에 대한 정보에 액세스 할 수 없습니다. 문자열을 업데이트하는 이벤트가 2 개 있고 핸들러에서 의 데이터를 모두 인쇄하도록 문자열을 업데이트하려면 이벤트 핸들러에서 두 문자열 모두에 액세스해야합니다. 이벤트 처리 클래스에서 변수에 변수를 저장하거나 이벤트를 발생시키는 클래스의 공용 속성으로 만들 수 있습니다. 이렇게하면 두 이벤트 핸들러에서 다른 이벤트의 업데이트 된 문자열에 액세스 할 수 있습니다.