问题
I have a thread running in a class that needs to update value of textbox but invoke does not appear in class.
Any idea how to do it?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.IO;
using CheckedBoxSerpCrawler;
namespace SERP_Crawler
{
class Crawl
{
public Crawl()
{
var t = new Thread(() =>
{
for (int i = 2; i < (pagesToScroll / 10); i++)
{
//Here i need to invoke CheckUrlList
}
});
t.SetApartmentState(ApartmentState.STA);
t.Start();
}//End Constructor
private void CheckUrlList(object sender, EventArgs e)
{
//Here update textbox
}
}
}
回答1:
IntelliSense shows this without any problems. I don't know what problem you have?
TextBox test = new TextBox();
if (test.InvokeRequired)
{
test.BeginInvoke(...);
}
The above mentioned should work, maybe you should have a look at http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invokerequired.aspx
Edit: To clarify a few things - test
is here your TextBox which value is ought to be changed. If you don't have access to the TextBox in your class, I like using events to start a method in your gui-control-class. But that's another story ;)
回答2:
You need to call Invoke on the textbox, not on the class that wants to update the textbox. If you look at the documentation for Invoke:
Executes the specified delegate on the thread that owns the control's underlying window handle.
then you can see that it is the thread that the textbox is running on that is important.
回答3:
Presumably this textbox is on a form, so add a method to the form that takes a string as a parameter, then inside this method use Invoke
to set the textbox's value. Inside your class, call this method on the form.
回答4:
If you want for your class to provide some notification mechanism, what you really want is an event, not to update a UI directly. In the context of a WinForms app, you can handle this event from your form and perform any Invoke
/BeginInvoke
work there.
Hopefully that makes sense. If not, try looking up .NET events to understand how they work.
But by all means, keep your class decoupled from your user interface. I'm not sure why anyone would encourage a move in the opposite direction.
来源:https://stackoverflow.com/questions/4747644/invoke-in-class-in-c-sharp-winforms