我有一个场景.(Windows Forms,C#,.NET)
UserControl_Load方法,则UI在加载方法执行的持续时间内变得无响应.伪代码看起来像这样:
代码1
UserContrl1_LoadDataMethod()
{
if (textbox1.text == "MyName") // This gives exception
{
//Load data corresponding to "MyName".
//Populate a globale variable List<string> which will be binded to grid at some later stage.
}
}
Run Code Online (Sandbox Code Playgroud)
它给出的例外是
跨线程操作无效:从创建它的线程以外的线程访问控件.
为了更多地了解这一点,我做了一些谷歌搜索,并提出了一个建议,如使用下面的代码
代码2
UserContrl1_LoadDataMethod()
{
if (InvokeRequired) // Line #1
{
this.Invoke(new MethodInvoker(UserContrl1_LoadDataMethod));
return;
}
if (textbox1.text == "MyName") // Now it wont give an exception
{
//Load data correspondin to "MyName"
//Populate a globale …Run Code Online (Sandbox Code Playgroud) 可能重复:
跨线程操作无效:从创建它的线程以外的线程访问控件
好的,我知道为什么这会给我这个错误:
跨线程操作无效:控制从其创建的线程以外的线程访问的"Form1".
但是......我怎样才能使这个可行?
System.Threading.Thread t = new System.Threading.Thread(()=>
{
// do really hard work and then...
listView1.Items.Add(lots of items);
lots more UI work
});
t.Start();
Run Code Online (Sandbox Code Playgroud)
我不关心Thread何时或如何完成,所以我并不关心任何花哨或过于复杂的atm,除非在新的Thread中使用UI时会更容易.
我正在尝试侦听COM端口,以便为SerialPort.DataReceived事件创建新的处理程序.逻辑很简单 - 我写了一些东西给TextBox1,按下Button1,我的文本应该在Label1中显示它自己.但我的应用程序不想运行,因为它抛出"交叉线程操作无效"错误.我做了一些搜索并找到了Invoke对象 - 我如何在我的例子中使用它?为什么我需要包含Invoke逻辑?
namespace WindowsApplication1
{
public partial class Form1 : Form
{
SerialPort sp = new SerialPort();
public Form1()
{
InitializeComponent();
sp.DataReceived += MyDataReceivedHandler;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void MyDataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
try
{
//sp.PortName = "COM3";
//sp.Open();
Label1.Text = sp.ReadLine();
}
catch (Exception exception)
{
RichTextBox1.Text = exception.Message + "\n\n" + exception.Data;
}
finally
{
sp.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{ …Run Code Online (Sandbox Code Playgroud)