内部异常:调用线程无法访问此对象,因为另一个线程拥有它

时间:2016-10-12 17:51:29

标签: c# wpf multithreading

每当我输入usename和密码时,它都会抛出异常。但当我单独运行它时,它运行得很好。

抛出异常:' System.Windows.Markup.XamlParseException'在PresentationFramework.dll

代码

private void testing()
{
    try
    {
        Thread newWindowThread = new Thread(new ThreadStart(() =>
        {
            SynchronizationContext.SetSynchronizationContext(
                new DispatcherSynchronizationContext(
                    Dispatcher.CurrentDispatcher));

            var loading_Win = new Loading_Window();

            loading_Win.Show();

            loading_Win.Closed += (s, ex) =>
                Dispatcher.CurrentDispatcher.BeginInvokeShutdown(
                    DispatcherPriority.Background);

            // Start the Dispatcher Processing
            System.Windows.Threading.Dispatcher.Run();
        }));

        // Set the apartment state
        newWindowThread.SetApartmentState(ApartmentState.STA);

        // Make the thread a background thread
        newWindowThread.IsBackground = true;

        // Start the thread
        newWindowThread.Start();
    }
    catch (Exception ex)
    { }
}

这是加载窗口cs

public partial class Loading_Window : MetroWindow
{
    public Random rnd = new Random();
    public static int intIteration = 1;
    private System.Windows.Forms.Timer timer1;

    public Loading_Window()
    {
        InitializeComponent();
        InitTimer();

        this.Closing += Loading_Window_Closing;
    }

    private void Loading_Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        //Process[] pro = null;
        //try
        //{
        //    pro = Process.GetProcessesByName("LeanPims");
        //    pro[0].Kill();
        //}
        //catch (Exception ex)
        //{ }
        //Process.GetCurrentProcess().Kill();
    }

    public void InitTimer()
    {            
        intIteration = 0;
        timer1 = new System.Windows.Forms.Timer();
        timer1.Tick += new EventHandler(timer1_Tick);
        timer1.Interval = 300; // in miliseconds
        timer1.Start();
    }

    public void timer1_Tick(object sender, EventArgs e)
    {
        intIteration += rnd.Next(1, 8);
        label1.Content = intIteration.ToString() + " %";

        try
        {
            if (intIteration >= 100)
            {
                timer1.Stop();
                timer1 = null;
                this.Close();
            }
        }
        catch (Exception ex) { }
    }
}

这是加载窗口xaml

<Viewbox Stretch="Fill">
    <Grid Height="500" Width="700" >
        <Image Stretch="Fill" Width="300" Height="350" gif:ImageBehavior.AnimatedSource="Images\Loading1.gif"  />
        <Rectangle HorizontalAlignment="Left" Height="45" Margin="298,228,0,0" StrokeThickness="2" VerticalAlignment="Top" Width="103" Fill="White"/>
        <Label Content="" x:Name="label1" HorizontalAlignment="Left" Height="36" Margin="327,236,0,0" VerticalAlignment="Top" Width="62" FontSize="18" FontFamily="Arial" Foreground="#FF837F7F" Background="{x:Null}" FontWeight="Bold"/>
        <Canvas x:Name="c1" HorizontalAlignment="Left" Height="406" Margin="112,38,0,0" VerticalAlignment="Top" Width="481"/>
    </Grid>
</Viewbox>

抛出异常:&#39; System.Windows.Markup.XamlParseException&#39;在PresentationFramework.dll

初始化&#39; System.Windows.Controls.Button&#39;抛出异常。

1 个答案:

答案 0 :(得分:0)

问题是您使用System.Windows.Forms.Timer设置label1.Content

您必须使用System.Windows.Threading.DispatcherTimer,或者必须使用以下方法手动调用Dispatcher:

Dispatcher.Invoke(() => label1.Content = intIteration.ToString() + " %");

所有其他与UI相关的调用都是如此。

如果您不想使用DispatcherTimer,那么您也必须这样做:

Dispatcher.Invoke(() => this.Close());

但是必须有更多与UI相关的陈述,因为XamlParseException表示Initialization of 'System.Windows.Controls.Button' threw an exception并且我在您发布的代码中没有看到单个Button

因此,检查是否存在任何其他与UI相关的调用,并使用正确的Dispatcher调用它们。 (如果您的应用中有多个Application.Current.Dispatcher,请注意不要在Loading_Window中使用Dispatchers。只需使用DispatcherDispatcher.CurrentDispatcher即可情况)。

最后但并非最不重要的是,我非常确定InnerException中还有另一个XamlParseException表示Initialization of 'System.Windows.Controls.Button' threw an exception。请检查一下。这可能是另一个原因,或者它可能与上面相同。它是在继承自Button的控件的构造函数中,或者它可能位于XAML中的某个位置。