ahmad05
ahmad05

Reputation: 458

get a value Returned from a Dispatcher timer Event handler?

how do i get a value returned from a event handler at a calling position?? what i would like to do is something like this

             ""  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;
                  }

Upvotes: 1

Views: 1801

Answers (1)

ΩmegaMan
ΩmegaMan

Reputation: 31616

Place the value on the member variable of the class which launched it. If need be use a lock to allow safe multi-processing. Since this is WPF make the class adhere to the INotifyPropertyChanged and bind it to a control on your screen.

Edit (Per the request of the OP)

I would use a background worker instead of a timer but the concept is the same (be wary not to update GUI controls in a timer, but the BW is designed to allow that).

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 ) );
        }
    }
 }

Here is where the work happens

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

And here is where you set the value safely for the GUI.

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

For another example with controls see on my blog : C# WPF: Threading, Control Updating, Status Bar and Cancel Operations Example All In One

Upvotes: 1

Related Questions