Silverlight,COM和线程

时间:2011-03-01 12:30:13

标签: multithreading silverlight com

我收到异常“无效的跨线程访问权限。” 我正在开发一个Silverlight应用程序。问题是我在一个线程中实例化对象(COM +对象)并尝试从另一个线程访问。这是我的应用程序的必要行为。 所以我想我需要说与COM的互操作处于MTAThread模式,但是我看不到要做到这一点 我知道问题,但我看不到解决方案。

任何帮助? 提前致谢

示例代码为:

using System.ComponentModel;
using System.Windows.Controls;
using System.Windows;
using System.Threading;
using System.Runtime.InteropServices.Automation;
using System;

namespace BackgroundWorkerTest
{
    public partial class MainPage : UserControl
    {
        Thread backgroundThread;
        dynamic _myspeech;
        static readonly object locker = new object();

        public MainPage()
        {
            InitializeComponent();

            backgroundThread = new Thread(StartScanProcess);
            backgroundThread.Start();
        }

        private void StartScanProcess(object sender, DoWorkEventArgs e)
        {
            StartScanProcess();
        }

        private void StartScanProcess()
        {
            lock (locker)
            {
                _myspeech = AutomationFactory.CreateObject("Sapi.SpVoice")
                _myspeech.Volume = 100;
            } 
        }

        private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            _myspeech.Speak(UIThreadId.Text); 
        }
    }
}

1 个答案:

答案 0 :(得分:1)

你尝试过使用过吗? 调度员?

像这样的东西: Dispatcher.BeginInvoke(委托                                        {                                            _myspeech.Speak(UIThreadId.Text);                                        });