简体   繁体   中英

WPF Update NON UI thread data based on UI thread control status

I have created a wpf applicaton. Which has one check box and two buttons for start and stop timer.After clicking on start button System.Timers.Timer aTimer will start running and calls the method checkboxstatus() to get the check box status and show it to the user. Even though if checkbox is checked am getting message as False. I have used the following code

public partial class MainWindow : Window
{  
    System.Timers.Timer aTimer = new System.Timers.Timer();
    bool ischeckboxchecked = false;

    public MainWindow()
    {
        InitializeComponent();
        aTimer.Elapsed += new ElapsedEventHandler(senddata_Tick);
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        aTimer.Interval = 3000;
        aTimer.Start();
    }
    public string checkboxstatus()
    {
        string data = string.Empty;
        ischeckboxchecked = false;
        Dispatcher.BeginInvoke((Action)(() =>
        {
            if (checkBox1.IsChecked == true)
            {
                ischeckboxchecked = true; //value is updating on each timer tick
            }
        }));
        data += ischeckboxchecked.ToString();
        return data;
    }
    private void senddata_Tick(Object sender, EventArgs args)
    {
        string postdata = string.Empty;
        postdata = checkboxstatus(); //every time am getting data as false
        MessageBox.Show(postdata);
    }
    private void button2_Click(object sender, RoutedEventArgs e)
    {
        aTimer.Stop();
    }

    private void checkBox1_Checked(object sender, RoutedEventArgs e)
    {

    }
}

any one suggest .......

You are invoking BeginInvoke on the dispatcher with your method. BeginInvoke immediately returns. Use Invoke instead to get a blocking call and return only after the Dispatcher operation has completed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM