c# - 我收到有关使用不同线程的错误消息?

标签 c# user-controls timer childwindow

当我单击我的 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);
    }
}

最佳答案

描述

您必须使用 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");
}

更多信息

窗体

WPF

关于c# - 我收到有关使用不同线程的错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8699839/

相关文章:

javascript - 如何在一定时间间隔后重复调用函数

c# - 在调用基本构造函数之前计算值

c# - 将自定义数据添加到 ADFS 身份验证

c# - 自己的WinForms控件闪烁且性能不佳

ios - 从 NSObject 重新加载 UITableView

Javascript 暂停计时器问题...无法计算

c# - 任务循环退出的 CancellationTokenSource 和退出标志之间的区别

c# - 多项目 Visual Studio 解决方案无法调试一个项目 DLL

c# - Gridview 中的 DataBind 用户控件

c# - .NET UserControl 接受按钮最佳实践?