这让我感到困惑,也许有人可以用我的无知来照亮教育之光.这是在C#windows应用程序中.我从一个线程访问列表框的内容.当我尝试像这样访问它
prgAll.Maximum = lbFolders.SelectedItems.Count;Run Code Online (Sandbox Code Playgroud)
我收到了错误.但是,这是我没有得到的部分.如果我注释掉那一行,那就是下一行foreach (string dir in lbFolders.SelectedItems)Run Code Online (Sandbox Code Playgroud)
执行得很好.
编辑:像往常一样,我缺乏沟通技巧.让我澄清一下.
我知道从除了创建它们之外的线程访问GUI项会导致问题.我知道访问它们的正确方法是通过委托.
我的问题主要在于:为什么我可以正常访问和迭代SelectedItems对象,但是当我尝试获取(未设置)它的Count属性时,它会爆炸.
所以,我正在尝试将文件更改为通知程序,并且我需要使文件框中的文本更新,只要文件的内容发生更改.这是我到目前为止:
string path = "C:/Users/Max/Dropbox/Public/IM.txt";
StringBuilder b = new StringBuilder();
private void Window_Loaded(object sender, EventArgs e)
{
TB.Text = File.ReadAllText(path);
b.Append(TB.Text);
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = path.Remove(path.Length - 6, 6);
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Filter = "*.txt";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
TB.SelectionStart = TB.Text.Length;
TB.ScrollToCaret();
}
private void OnChanged(object source, FileSystemEventArgs e)
{
TB.Text = File.ReadAllText(path);
}
Run Code Online (Sandbox Code Playgroud)
这似乎正确地引发了事件,但是一旦触及OnChanged事件中的代码,程序退出,没有错误或任何事情,只需关闭.我试图阻止它关闭,我甚至尝试将e.Cancel放在formclosing事件下,但似乎没有任何效果.有任何想法吗?如果需要,我可以提供更多信息.
我正在尝试从另一个类填充列表视图,但我发现这个错误:"跨线程操作无效:控制'listView1'从其创建的线程以外的线程访问."
在我的班级中,我声明我的列表视图是这样的:
class CheckBlankPages
{
public String[] pdfFiles
{ get; set; }
ListView _ListVireRef;
public int NrCRT = 1;
public CheckBlankPages(String[] pdfFiles = null, ListView listView = null)
{
this.pdfFiles = pdfFiles;
_ListVireRef = listView;
}
public void StartCheckingPDF()
{
foreach (string pdf in pdfFiles)
{
String[] itm = { (NrCRT++).ToString(), pdf };
ListViewItem item = new ListViewItem(itm);
_ListVireRef.Items.Add(item);
}
}
}
Run Code Online (Sandbox Code Playgroud)
在我的MainForm中我使用此代码:
DialogResult rezultat = openFileDialog1.ShowDialog();
if (rezultat == DialogResult.OK)
{
CheckBlankPages ck = new CheckBlankPages(openFileDialog1.FileNames, listView1);
Thread CheckPDFs …Run Code Online (Sandbox Code Playgroud) 这是我在Form2上设置一些组件状态的一种小方法.当我从Form2上调用它来加载它时.工作正常,但当我从Form1调用它(需要更新一些状态)时,我得到一个例外:
System.Windows.Forms.dll中发生了未处理的"System.InvalidOperationException"类型异常
附加信息:跨线程操作无效:控制'button1'从其创建的线程以外的线程访问.
public void SetleMotor1()
{
button1.Enabled = true;
button2.Enabled = false;
if (Form1.Motor1.Calibstate == 3)
label4.Text = "Befejezve";
else
label5.Text = "Megállt";
if (Form1.Motor1.Calibrated)
{
label21.Text = "Igen";
label6.Text = Convert.ToString(Form1.Motor1.MMImp);
}
else
{
label21.Text = "Nem";
label6.Text = "-";
}
}
Run Code Online (Sandbox Code Playgroud)
拜托,我在这里错过了什么?
下面是Form1中调用Form2上的方法的代码:
void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// reading the data etc etc etc...then evaluating:
case 1:
if ((data[1] == 40) && (Motor1.Calibstate == 3))
{
long impulses = (65536 * data[2] + 256 * …Run Code Online (Sandbox Code Playgroud) 我的主表单Form1运行了程序的主要部分.
我有一个单独的线程开始执行算法.
当我从新线程运行该方法时,方法MyAlgorithm()我得到错误
InvalidOperationException,消息"控制控件名称从其创建的线程以外的线程访问".
如何返回到原始线程,以便我可以运行该方法来更新具有最新值的文本框?
这是我想要运行的方法,包含在我的应用程序中的主类Form1中.
// Reset the results values
public void ShowResults()
{
while (true)
{
loopsNum.Text = Convert.ToString(resultLoopsNum);
nodesVisitedNum.Text = Convert.ToString(resultNodesVisitedNum);
nodesResolvedNum.Text = Convert.ToString(resultNodesResolvedNum);
cpuLoopsNum.Text = Convert.ToString(resultCpuLoopsNum);
shortestPathCostNum.Text = Convert.ToString(resultShortestPathCost);
}
}
Run Code Online (Sandbox Code Playgroud)
我查看了Invoke()方法,但我不知道如何从thread方法获取Form1的原始实例.
我正在调用我的线程......
// Set the algorithm method up in it's own thread
Thread thread = new Thread(new ThreadStart(MyAlgorithm));
// Run the algorithm
thread.Start();
Run Code Online (Sandbox Code Playgroud) 我有一个usercontrol和两个类,我想将我的class1的结果打印到usercontrol.I我正在使用这一行从类发送结果
((merge.MyControl)(MyControlInstance)).CLIDisplay = e.WorkItem.CustomerId;
Run Code Online (Sandbox Code Playgroud)
我的控件属性显示结果是
public string CLIDisplay
{
get { return lblResultCLI.Text; }
set
{
lblResultCLI.Text = value;
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我把一个类调到我的c#表单时,我得到了Exception
An exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll but was not handled in user code
Additional information: Cross-thread operation not valid: Control 'tbxEvents' accessed from a thread other than the thread it was created on.
Run Code Online (Sandbox Code Playgroud) 我试过这个。 /sf/answers/9944861/
喜欢 toolStripStatusLabel1.InvokeRequired
但toolStripStatusLabel1没有InvokeRequired
我也试过这个。 /sf/answers/1108190471/
它像无效参数一样出错
SetTextCallback d = new SetTextCallback(SetText);
form.Invoke(d, new object[] { form, ctrl, text });
当我使用
ThreadHelperClass.SetText(this, toolStripStatusLabel1, "This text was set safely.");
但我使用时不会出错 textBox
我的代码有方法等待bool另一个使用线程在后台运行的方法。
Thread t = new Thread(TestRemoteDB);
t.Start();
// In TestRemoteDB() will call updateRemoteDBStatus()
Run Code Online (Sandbox Code Playgroud)
像这样
private void updateRemoteDBStatus(bool successful)
{
if (successful)
{
toolStripStatusLabel4.Text = "OK!";
toolStripStatusLabel4.ForeColor = Color.Green;
}
else
{
toolStripStatusLabel4.Text = "Error!";
toolStripStatusLabel4.ForeColor = Color.Red;
}
}
Run Code Online (Sandbox Code Playgroud) 我需要一些帮助。我开始使用 c#,但对事件处理和线程还不是很熟悉。作为一个初学者,随着时间和接触的增加,我想了解更多关于这些高级主题的知识并进行改进,并希望这里的所有人都能帮助我。
我遇到了“跨线程操作无效:从创建它的线程以外的线程访问控制‘名为 stackStatus’的文本框控件”的问题。我一整天都在尝试解决问题,但根本无济于事。我被困住了。:-( 程序遇到异常,无法继续顺利执行。
我已阅读以下主题并尝试了一些事情,但我想我仍然缺少一些东西。如果有人能在这里帮助我,我将不胜感激。谢谢。
跨线程操作无效:从创建它的线程以外的线程访问控制“textBox1”
这是代码的大部分部分:
private void createCloud_Click(object sender, EventArgs e)
{
CreateCloud(); //start creation method
stackStatus.Text = "Creating stack..."; //updates the cloud status textbox
stackStatus.Refresh();
Cursor.Current = Cursors.WaitCursor; //change the cursor to wait state
Start_Describestack(); //call describe method to find out the status of cloud creation progress
Task.Delay(12000); // wait 12s in case not ready
Start_Describestack(); // call again describe method to find out the cloud creation progress status
Cursor.Current = Cursors.Default; //put cursor on …Run Code Online (Sandbox Code Playgroud) 我正在编写简单的应用程序来加载csv文件,并在c#代码中启动新线程以使用以下代码加载重csv文件:
Thread workerThread = new Thread(DoWork);
workerThread.Priority = ThreadPriority.Highest;
workerThread.Start();
Run Code Online (Sandbox Code Playgroud)
进入DoWork我尝试运行此代码:
public void DoWork()
{
label1.Text = "ok";
}
Run Code Online (Sandbox Code Playgroud)
但是当收到标签行我得到这个错误:
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll
Additional information: Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on.
Run Code Online (Sandbox Code Playgroud)
会发生什么事?谢谢.
我知道这个问题在这里被问了太多次,但我似乎没有修复它所以我发布了一个新问题.
我有两种形式Form1和Form2.Form2 通过将其最顶层属性设置为true,在form1上显示为叠加层.我有一个类为form1处理事务,如果找到所需的值,它会在STA线程中打开form2作为form1上的叠加层.
但是,如果在接下来的几秒钟内找不到该值,则类处理是一个连续的过程,然后我需要关闭已经打开的form2,由于上述异常,我目前无法做到这一点.
这是我的代码:
private void runBrowserThread(bool markerFound)
{
try
{
var th = new Thread(() =>
{
if (markerFound == true)
{
if (Application.OpenForms.OfType<webForm>().Count() == 0)
{
webForm frm = new webForm();
frm.Show();
}
Application.Run();
}
else
{
if (Application.OpenForms.OfType<webForm>().Count() == 1)
{
Form fc = Application.OpenForms["webForm"];
if (fc != null)
fc.Close(); //**This line causes cross thread exception**
}
}
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
} catch (Exception)
{
//...
}
}
Run Code Online (Sandbox Code Playgroud)
任何建议都会非常感激.
如何与后台线程一起维护前台线程.如果我尝试在工作中将项添加到列表中,它会给我一个跨线程异常.
我Timer在一个方法中设置了一个间隔为1000每秒钟它将另一个相应的字符Textbox键入一个(几乎自动输入).当我检查_currentTextLength == _text.Length我得到线程错误"调用线程无法访问此对象,因为另一个线程拥有它."
public void WriteText(string Text)
{
timer = new Timer();
try
{
_text = Text;
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed_WriteText);
timer.Interval = 1000;
timer.Enabled = true;
timer.Start();
}
catch
{
MessageBox.Show("WriteText timer could not be started.");
}
}
// Write Text Timer Event
void timer_Elapsed_WriteText(object sender, ElapsedEventArgs e)
{
TextBoxAutomationPeer peer = new TextBoxAutomationPeer(_textBox);
IValueProvider valueProvider = peer.GetPattern(PatternInterface.Value) as IValueProvider;
valueProvider.SetValue(_text.Substring(0, _currentTextLength));
if (_currentTextLength == _text.Length) // Error here
{
timer.Stop(); …Run Code Online (Sandbox Code Playgroud) 首先,我正在创建新线程,因为我想在表单上显示光标位置。所以,这就是我所做的,在课堂上,我创建了一个线程并使用该线程运行该方法,该方法将光标位置分配给我的表单上的标签。
public partial class Main : Form
{
public Main()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}
private void GetCurLoc()
{
while (true)
{
PosX.Text = MousePosition.X.ToString();
PosY.Text = (Int32.Parse(PosYMax.Text) - MousePosition.Y).ToString();
}
}
private void Main_Load(object sender, EventArgs e)
{
Thread curLoc = new Thread(new ThreadStart(GetCurLoc));
curLoc.Start();
}
}
Run Code Online (Sandbox Code Playgroud)
但是,该应用程序会消耗大量 CPU 和电量。为什么一个线程会消耗这样的CPU?对我来说,似乎我的线程创建正在造成资源泄漏。
请帮忙。