调用onclick on按钮将代码放入C#中的不同线程中

我有一个启动相机的按钮。 我想有时候开始拍摄相机,不按下按钮。

代码:

private async void StartCamera() { if (!CameraList.HasItems) //-------> CameraList is in the UI { MessageArea.Text = "No cameras found; cannot start processing"; return; } // Clean leading/trailing spaces in API keys. Properties.Settings.Default.FaceAPIKey = Properties.Settings.Default.FaceAPIKey.Trim(); Properties.Settings.Default.EmotionAPIKey = Properties.Settings.Default.EmotionAPIKey.Trim(); Properties.Settings.Default.VisionAPIKey = Properties.Settings.Default.VisionAPIKey.Trim(); // Create API clients. _faceClient = new FaceServiceClient(Properties.Settings.Default.FaceAPIKey); _emotionClient = new EmotionServiceClient(Properties.Settings.Default.EmotionAPIKey); _visionClient = new VisionServiceClient(Properties.Settings.Default.VisionAPIKey); // How often to analyze. _grabber.TriggerAnalysisOnInterval(Properties.Settings.Default.AnalysisInterval); // Reset message. MessageArea.Text = ""; // -------> MessageArea is in the UI // Record start time, for auto-stop _startTime = DateTime.Now; await _grabber.StartProcessingCameraAsync(CameraList.SelectedIndex); // This is the problem, with the previous two I just can skip it, but here I can't avoid the CameraList } private async void StartButton_Click(object sender, RoutedEventArgs e) { StartCamera(); } 

我必须告诉我CameraList变量是一个UIcombobox。

因此,当我尝试使用StartCamera函数时,我得到一个exception,说{“调用线程无法访问此对象,因为另一个线程拥有它。”}

当我尝试使用startButton UI并使用时,同样的事情很开心:

  StartButton.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent)); 

在之前的一个post中,我被告知:“你只能从最初创建它的线程中访问一个UI元素,即UI线程。所以你不能在后台线程上运行你的代码。这与你原来的无关关于如何调用事件处理程序的问题。如果你有其他问题,请问一个新问题。“

我在这里。

我打算为你发布一些示例代码,但是这个post有很多好的答案如何从C#中的另一个线程更新GUI? 。

基本上,您必须使用委托来回调运行ui的线程。 这是因为您希望序列化所有ui修改/输入。 您不希望2个不同的线程同时在ui中更改某些内容。 根据我的经验,用锁定环绕你正在回调的方法并不是一个坏主意,就像增加一层防御竞争条件一样。

无论如何,请看一下这个链接。 它应该会帮助你。