且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我应该如何从后台运行线程获取表单的价值

更新时间:2023-02-23 22:03:15

嘿,我编写了一个程序,该程序需要从另一个线程在Windows窗体上调用函数.发生问题是因为Windows窗体不是线程安全的.

解决此问题的方法是通过类似这样的方式在Windows窗体线程消息循环中调用一个函数

Hey I have a program that I wrote that requires calling function on a windows form from a different thread. The problem occurs because windows forms are not thread safe.

The way to get around this is to invoke a function in the windows form threads message loop via something like this

// declare a delegate to pass to the message queue
delegate void funcDelegate();

// Declare the function you want your windows form to call
public void function()
{
    // If the function is being called in the same thread
    // as the form Invoke is not required, so call what needs
    // to be called
    if (!WindowsFormName.InvokeRequired)
    {
        textbox1.text = value.ToString();
        MessageBox.Show(WindowsFormName);
    }
    // If not invoke this function in the message queue so the
    // Window form calls it when it is ready.
    else
        WindowsFormName.Invoke(new funcDelegate(function));
}



该代码应写在您编写后台线程的区域中.这个想法是,当您的后台线程需要更改表单上的值并显示消息框时,您可以从后台线程中调用该函数.

该函数将运行,并且所需的调用将为true,因为它不在Windows窗体线程中.这会将相同的功能放入Windows窗体的消息队列中.当表单调用该函数时(由于它位于消息队列中),InvokeRequired将为false,并且代码将运行以更改表单值并显示消息框.

我确定您可以将计数增加到25,所以我不再赘述,但是,如果您希望使用参数调用函数,则需要对代码进行一些细微的更改.例如,您将不得不更改功能以添加参数



This code should be written in the area where you background thread is written. The idea is, that when you background thread needs to change the value on the form and show the message box, you call the function from within you background thread.

The function will run, and invoke required will be true since it is not in the windows form thread. This will put the same function into the message queue of the windows form. When the form calls the function, which it will because it is in the message queue, InvokeRequired will be false and the code will run to change the forms values and display the message box.

I''m sure you can handle the counting to 25 so I won''t go into that, however if you wish to call a function with parameters, there are some tiny changes that need to be made to the code. for example you would have to change the function to add the parameters

public void function(int param1)



和代表来反映这一点



and the delegate to reflect that

delegate void funcDelegate(int param1);



然后是invoke语句,因为我从未使用过它,所以我不太确定这一点,但是我认为您只是将参数作为对象数组传递.如果您在Google上查找Invoke c#,就会发现有很多内容,但是我认为它会像



and then the invoke statement, I''m not completely sure about this one because i never used it, however I think you just pass the parameters as an array of object. If you look up Invoke c# on google there is plenty on it, but I think it would be something like

WindowsFormName.Invoke(new funcDelegate(function),
           new object[] {IntVariableToBePassed});



注意:WindowsFormName是您的表单的名称.

希望有帮助,
mata89



NOTE: WindowsFormName is the name of you form.

Hope that helps,
mata89