1

当我单击我的 ActionButton 时,会启动一个计时器,在 3 秒后,它必须触发一个方法以将当前 ContentPage 更改为另一个页面。但我收到一条消息:调用线程无法访问此对象,因为另一个线程拥有它。我不明白我做错了什么。但是,如果我将 ChangeContent() 方法放在 click_event 中,它可以工作,但在 _tm_elapsed 中它不起作用?

using smartHome2011.FramePages;
using System.Timers;

public partial class AuthenticationPage : UserControl
{
    private MainWindow _main;
    private Storyboard _storyboard;
    private Timer _tm = new Timer();
    private HomeScreen _homeScreen = new HomeScreen();

    public AuthenticationPage(MainWindow mainP)
    {
        this.InitializeComponent();
        _main = mainP;
    }

    private void ActionButton_Click(object sender, System.EventArgs eventArgs)
    {
        _main.TakePicture();
        identifyBox.Source = _main.source.Clone();
        scanningLabel.Visibility = Visibility.Visible;
        _storyboard = (Storyboard) FindResource("scanningSB");
        //_storyboard.Begin();
        Start();
    }

    private void Start()
    {
        _tm = new Timer(3000);
        _tm.Elapsed += new ElapsedEventHandler(_tm_Elapsed);
        _tm.Enabled = true;
    }

    private void _tm_Elapsed(object sender, ElapsedEventArgs e)
    {
        ((Timer) sender).Enabled = false;
        ChangeContent();
        //MessageBox.Show("ok");
    }

    private void ChangeContent()
    {
        _main.ContentPage.Children.Clear();
        _main.ContentPage.Children.Add(_homeScreen);
    }
}
4

3 回答 3

4

描述

您必须使用Invoke来确保 UI 线程(创建控件的线程)将执行该操作。

1. 如果您正在使用 Windows 窗体,请执行此操作

样本

private void ChangeContent()
{
    if (this.InvokeRequired)
    {
        this.Invoke(new MethodInvoker(ChangeContent));
        return;
    }

    _main.ContentPage.Children.Clear();
    _main.ContentPage.Children.Add(_homeScreen);
}

2. 如果您正在使用 WPF,请执行此操作

private void _tm_Elapsed(object sender, ElapsedEventArgs e)
{
    ((Timer) sender).Enabled = false;
    this.Dispatcher.Invoke(new Action(ChangeContent), null);
    //MessageBox.Show("ok");
}

更多信息

Windows 窗体

WPF

于 2012-01-02T10:43:20.957 回答
1

Elapsed发生这种情况时执行的逻辑在Timer与其余代码不同的线程上运行。此线程无法访问主/GUI 线程上的对象。

该线程应该可以帮助您了解如何操作:如何从 C# 中的另一个线程更新 GUI?

于 2012-01-02T10:44:18.680 回答
1

我怀疑您使用的是 System.Threading.Timer。您可以通过仅使用 Windows.Forms 计时器来避免跨线程操作:http: //msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx 该计时器使用常规消息并且事件发生在UI 的同一线程。使用的事件不再称为“Elapsed”,但“Tick”在此处阅读文档:http: //msdn.microsoft.com/en-us/library/system.windows.forms.timer.tick.aspx

于 2012-01-02T10:59:32.450 回答