相关疑难解决方法(0)

如何将事件回调变为我的win表单线程安全?

当您从表单中订阅对象上的事件时,您实际上是将对回调方法的控制权移交给事件源.您不知道该事件源是否会选择在不同的线程上触发事件.

问题是,当调用回调时,您不能假设您可以对表单进行更新控制,因为如果在与运行表单的线程不同的线程上调用事件回调,则有时这些控件将引发异常.

.net c# events multithreading winforms

38
推荐指数
3
解决办法
3万
查看次数

C# - 无法使用Invoke()从后台线程附加文本进行控制

问候,我在从C#中的工作线程调用richTextBox时遇到问题.我正在使用InvokeRequired/Invoke方法.请看我的代码:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void ThreadSafe(MethodInvoker method)
    {
        if (InvokeRequired)
            Invoke(method);
        else
            method();
    }

    private void WorkerThread(object data)
    {
        string msg = "\nhello, i am thread " + data.ToString();
        ThreadSafe(delegate
        {
            richTextBox1.AppendText(msg);
        });
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Thread[] workers = new Thread[3];

        for (int i = 0; i < 3; i++)
        {
            workers[i] = new Thread(WorkerThread);
            workers[i].Start(i);
            string msg = "\nthread " + i.ToString() + "started!"; …
Run Code Online (Sandbox Code Playgroud)

c# user-interface controls multithreading invoke

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

C#.NET中的线程和交叉线程,如何从另一个线程更改ComboBox数据?

我需要在我的应用程序中使用线程,但我不知道如何执行交叉线程操作.

我希望能够从另一个线程更改表单对象的文本(在本例中为组合框),我得到错误:

Cross-thread operation not valid: Control 'titlescomboBox' accessed from a thread other than the thread it was created on.
Run Code Online (Sandbox Code Playgroud)

我真的不明白如何使用调用和开始调用函数,所以我真的在寻找一个简单的例子和​​解释,所以我可以学习它.

此外,任何初学者教程都会很棒,我发现了一些,但是他们都是如此不同,我不明白我需要做什么才能执行交叉线程操作.

这是代码:

    // Main Thread. On click of the refresh button
    private void refreshButton_Click(object sender, EventArgs e)
    {
        titlescomboBox.Items.Clear();
        Thread t1 = new Thread(updateCombo);
        t1.Start();
    }

    // This function updates the combo box with the rssData
    private void updateCombo()
    {
        rssData = getRssData(channelTextBox.Text);       // Getting the Data
        for (int i = 0; i < rssData.GetLength(0); i++)   // Output it …
Run Code Online (Sandbox Code Playgroud)

c# multithreading

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

标签 统计

c# ×3

multithreading ×3

.net ×1

controls ×1

events ×1

invoke ×1

user-interface ×1

winforms ×1