Could anyone help me i have a problem I'm trying to get this code to work in the background via threadpool but i cannot seem to get it to work i keep getting this error:
Cross-thread operation not valid: Control 'ListBox3' accessed
from a thread other than the thread it was created on.
Here is the code i am using:
private void DoWork(object o)
{
var list = ListBox3;
var request = createRequest(TxtServer.Text, WebRequestMethods.Ftp.ListDirectory);
using (var response = (FtpWebResponse)request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream, true))
{
while (!reader.EndOfStream)
{
list.Items.Add(reader.ReadLine());
ResultLabel.Text = "Connected";
}
}
}
}
}
Gets a value indicating whether the caller must call an invoke method when making method calls to the control because the caller is on a different thread than the one the control was created on. public: property bool InvokeRequired { bool get(); }; C# Copy.
CheckForIllegalCrossThreadCalls parameter. The BlueZone ActiveX control is a legacy control that was developed before . NET. It has functionality that will hook into the container window's message processing to intercept messages.
You can access controll by do this
Invoke(new Action(() => {Foo.Text="Hi";}));
You need to invoke a delegate to update the list. See this MSDN example.
This extension method solves the problem too.
/// <summary>
/// Allows thread safe updates of UI components
/// </summary>
public static void InvokeEx<T>(this T @this, Action<T> action) where T : ISynchronizeInvoke
{
if (@this.InvokeRequired)
{
@this.Invoke(action, new object[] { @this });
}
else
{
action(@this);
}
}
Use in your worker thread as follows
InvokeEx(x => x.MyControl.Text = "foo");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With