相关疑难解决方法(0)

调用任何交叉线程代码的最佳方法?

我知道之前已经问过这个问题,但我正在寻找一种方法:

  1. 简化安全交叉线程代码的创建.
  2. 在任何情况下重用此代码(没有Windows窗体引用).

这是我到目前为止,但我想删除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但保持相同的功能?

.net c# invoke

36
推荐指数
4
解决办法
4万
查看次数

从其创建的线程以外的线程访问的vb.net

我试图将文本设置为标签Label_caller.Text = phone_number,我收到此错误:"System.InvalidOperationException:跨线程操作无效:控件'Label_caller'从其创建的线程以外的线程访问." 我该如何克服这个问题?我如何使用关键字Me?

vb.net multithreading text label

6
推荐指数
1
解决办法
9218
查看次数

如何从其他线程向listBox添加项?

我正在开始新的主题:

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".

我该怎么办呢?

c# multithreading

2
推荐指数
1
解决办法
1万
查看次数

在新线程上创建类的实例

我正在创建一个位于 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 元素(例如组合框)。

c# winforms

-1
推荐指数
1
解决办法
725
查看次数

标签 统计

c# ×3

multithreading ×2

.net ×1

invoke ×1

label ×1

text ×1

vb.net ×1

winforms ×1