2012-11-01 54 views
1

我如何從一個事件處理程序在一個調用位置返回一個值? 我想要做的就是這樣的事情獲取值從分派器計時器返回事件處理程序?

   "" int a = timer.Elapsed += new ElapsedEventHandler((sender, e) => 
       on_time_event(sender, e, draw, shoul_l)); "" 


       timer_start = true; 
       timer.Interval = 2000; 
       timer.Start(); 
       timer.Elapsed += new ElapsedEventHandler((sender, e) => 
       on_time_event(sender, e, draw, shoul_l)); 


       private int on_time_event(object sender, ElapsedEventArgs e, 
       DrawingContext dcrt, System.Windows.Point Shoudery_lefty) 
       { 
        . 
        . 
        . 
        . 
        return a_value; 
        } 
+0

如何和ESP當你想收到的價值? –

+0

我在這裏想要的只是返回一個整數值,只要定時器事件處理程序調用 – ahmad05

+0

'回來' - 在哪裏以及如何? –

回答

1

廣場上推出它的類的成員變量的值。如果需要使用鎖來允許安全的多處理。由於這是WPF,因此該類將遵循INotifyPropertyChanged並將其綁定到屏幕上的控件。

編輯(每OP的請求)

我會用一個背景工人而不是一個計時器的但概念是相同的(警惕不以定時器更新GUI控件,但BW被設計以允許)。

public partial class Window1 : Window, INotifyPropertyChanged 
{ 
    BackgroundWorker bcLoad = new BackgroundWorker(); 
    private string _data; 

    public string Data 
    { 
     get { return _data;} 
     set { _data = value; OnPropertyChanged("Data"); } 
    } 

    public Window1() 
    { 
     InitializeComponent(); 

     bcLoad.DoWork    += _backgroundWorker_DoWork; 
     bcLoad.RunWorkerCompleted += _backgroundWorker_RunWorkerCompleted; 
     bcLoad.RunWorkerAsync(); 
    } 
    protected virtual void OnPropertyChanged(string propertyName) 
    { 
     PropertyChangedEventHandler handler = PropertyChanged; 
     if (handler != null) 
     { 
      handler(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 
} 

這裏是工作的場所

void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e) 
{ 
    e.Result = "Jabberwocky"; 
} 

這裏是你的GUI設置的值安全。

void _backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) 
{ 
    Data = (string) e.Result; 
} 

另一個例子,與對照看我的博客:C# WPF: Threading, Control Updating, Status Bar and Cancel Operations Example All In One

+0

有點代碼可能非常有用非常業餘時間,當涉及到C#和WPF – ahmad05

+1

@ ahmad05有一個例子,我建議一個後臺工作,但概念是相同的。 – OmegaMan

相關問題