我知道之前已经问过这个问题,但我正在寻找一种方法:
这是我到目前为止,但我想删除Windows窗体引用.有任何想法吗?
public delegate void SafeInvokeDelegate(System.Action action);
public class SafeInvoke
{
private readonly System.Windows.Forms.Control _threadControl;
public SafeInvoke()
{
_threadControl = new System.Windows.Forms.Control();
}
public void Invoke(System.Action action)
{
if (_threadControl.InvokeRequired)
_threadControl.Invoke(new SafeInvokeDelegate(Invoke), new object[] {action});
else if (action != null) action();
}
}
Run Code Online (Sandbox Code Playgroud)
上面的类可能会这样使用:
SafeInvoke _safeInvoker = new SafeInvoke();
void SafeClearItems()
{
_safeInvoker.Invoke(delegate
{
listView1.Items.Clear();
});
}
Run Code Online (Sandbox Code Playgroud)
我如何删除SafeInvoke类中的System.Windows.Forms.Control但保持相同的功能?
我试图将文本设置为标签Label_caller.Text = phone_number,我收到此错误:"System.InvalidOperationException:跨线程操作无效:控件'Label_caller'从其创建的线程以外的线程访问." 我该如何克服这个问题?我如何使用关键字Me?
我正在开始新的主题:
Thread t = new Thread(UpdateListOutput);
t.IsBackground = true;
t.Start();
Run Code Online (Sandbox Code Playgroud)
UpdateListOutput:
void UpdateListOutput()
{
while (true)
{
if (!string.IsNullOrEmpty(engineOutput))
{
OutputBox.Items.Add(engineOutput);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我发现错误:
跨线程操作无效:控制从其创建的线程以外的线程访问的"OutputBox".
我该怎么办呢?
我正在创建一个位于 DLL 中且无法修改的类的实例。它加载图像需要很长时间,这会冻结 WinForms UI。
我可以在新线程上实例化该类吗?
var images = new AppImages(); // This to execute on new thread?
var cboData = new List<string>();
foreach(var image in images)
{
cboData.Add(image);
}
comboBox.DataSource = cboData;
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用
private void My()
{
var images = ThreadPool.QueueUserWorkItem(GetAppImages);
var cboData = new List<string>();
foreach(var image in images)
{
cboData.Add(image);
}
comboBox.DataSource = cboData;
}
private AppImages GetAppImages()
{
return new AppImages();
}
Run Code Online (Sandbox Code Playgroud)
但 threadPool 不返回任何值,它只是执行代码,我需要新实例稍后在代码中使用它。
另外,我可以在新线程中调用整个逻辑,因为存在 UI 元素(例如组合框)。