我有一个场景.(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) 可能重复:
跨线程操作无效:从创建它的线程以外的线程访问控件
public void CheckUnusedTabs(string strTabToRemove)
{
TabPage tp = TaskBarRef.tabControl1.TabPages[strTabToRemove];
tp.Controls.Remove(this);
TaskBarRef.tabControl1.TabPages.Remove(tp);
}
Run Code Online (Sandbox Code Playgroud)
我试图使用上面的代码关闭Windows应用程序的tabcontrol中的选项卡,我遇到了错误:
跨线程操作无效.
怎么解决这个?
我正在尝试侦听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) 我试图从一个不同的线程访问一个表单到创建表单的表单,最后得到一个错误:
跨线程操作无效
码:
public static void MakeTopMost(Form form)
{
SetWindowPos(form.Handle, HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);
}
Run Code Online (Sandbox Code Playgroud)
我正在传递一个在另一个线程中运行的表单.我试过测试InvokeRequired,但总是假的.
我是线程新手.
获取错误:跨线程操作无效:控制'label1'从其创建的线程以外的线程访问.
码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
string CONNECTING = "Connecting to server...";
string GETTING_DATA = "Getting data...";
string CONNECT_FAIL = "Failed to connect!";
string CONNECT_SUCCESS = "Connection established!";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Thread t1 = new Thread(run);
t1.Start();
}
public void run() {
label1.Text = CONNECTING; …Run Code Online (Sandbox Code Playgroud)