gpt4 book ai didi

c# - 跨线程操作在 Windows 窗体中无效

转载 作者:太空狗 更新时间:2023-10-29 22:05:12 24 4
gpt4 key购买 nike

有人能帮我吗我有一个问题我试图通过线程池让这段代码在后台工作但我似乎无法让它工作我不断收到这个错误:

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

这是我使用的代码:

private void DoWork(object o)
{
var list = ListBox3;

var request = createRequest(TxtServer.Text, WebRequestMethods.Ftp.ListDirectory);

using (var response = (FtpWebResponse)request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream, true))
{
while (!reader.EndOfStream)
{
list.Items.Add(reader.ReadLine());
ResultLabel.Text = "Connected";
}
}
}
}
}

最佳答案

你可以通过这样做访问控制

 Invoke(new Action(() => {Foo.Text="Hi";}));

关于c# - 跨线程操作在 Windows 窗体中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13945225/

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