gpt4 book ai didi

c# - 跨线程错误,但没有使用线程

转载 作者:太空狗 更新时间:2023-10-30 00:10:53 25 4
gpt4 key购买 nike

我不断得到

Cross-thread operation not valid: Control 'keyholderTxt' accessed from a thread other than the thread it was created on.

关于项目中各种形式的各种控件,我用谷歌搜索并发现了很多关于如何从各种线程访问内容的回复,但据我所知,我没有在我的项目中使用任何其他线程,并且更改代码中数百个可能的位置将是难以管理的。

它从来没有发生过,只是因为我添加了各种看似无关的代码。我在下面列出了我遇到错误的地方的示例,但它在整个解决方案的很多地方都发生过。

keyholderTxt.Text = "Keyholders Currently In:\r\n \r\n Nibley 1: + keyholders";

或者这个,一个更好的例子,因为你可以看到从表单加载到错误发生的一切:

      private void Identification_Load(object sender, System.EventArgs e)
{
_Timer.Interval = 1000;
_Timer.Tick += new EventHandler(_Timer_Tick);
_Timer.Start();

txtIdentify.Text = string.Empty;
rightIndex = null;

SendMessage(Action.SendMessage, "Place your finger on the reader.");

if (!_sender.OpenReader())
{
this.Close();
}

if (!_sender.StartCaptureAsync(this.OnCaptured))
{
this.Close();
}
}

void _Timer_Tick(object sender, EventArgs e)
{
this.theTime.Text = DateTime.Now.ToString();
}

private void OnCaptured(CaptureResult captureResult)
{
txtIdentify.Clear();
//other stuff after the cross thread error
}

不关闭datareader之类的事情会导致这种错误吗?

我正在使用 Windows 窗体应用程序。

最佳答案

我怀疑罪魁祸首是这个:

if (!_sender.StartCaptureAsync(this.OnCaptured))

我不知道您使用的 API,但根据名称,我认为回调方法 (OnCaptured) 是在工作线程上调用的,而不是在 UI 线程上调用的。所以你需要使用 Invoke 在 UI 线程上执行操作:

private void OnCaptured(CaptureResult captureResult)
{
if (InvokeRequired)
{
Invoke(new System.Action(() => OnCaptured(captureResult)));
return;
}

txtIdentify.Clear();
// ...
}

关于c# - 跨线程错误,但没有使用线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18486922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com