invoke
Simple Python task execution
Welcome to Invoke! — Invoke documentation
I would like to invoke a private static method. I have its name. I've heard it can be done using Java reflection mechanism. How can I do it?
EDIT: One problem I encountered when trying to invoke the method is how to specify the type of its argument. My method receives one argument and its type is Map. Therefore I cannot do Map<User, String>.TYPE
(In run time there's no such a thing as Map because of Java Type erasure). Is there another way to get the method?
Source: (StackOverflow)
If I have two variables:
Object obj;
String methodName = "getName";
Without knowing the class of obj
, how can I call the method identified by methodName
on it?
The method being called has no parameters, and a String
return value. It's a getter for a Java bean.
Source: (StackOverflow)
What is the difference between Invoke and DynamicInvoke in delegates? Please give me some code example which explain difference between that two methods.
Source: (StackOverflow)
Can anybody please explain this statement written on this link
Invoke(Delegate):
Executes the specified delegate on the thread that owns the control's underlying window handle.
Can anybody explain what this means (especially the bold one) I am not able to get it clearly
Source: (StackOverflow)
Just wondering what the difference between BeginInvoke()
and Invoke()
are?
Mainly what each one would be used for.
EDIT: What is the difference between creating a threading object and calling invoke on that and just calling BeginInvoke()
on a delegate? or are they the same thing?
Source: (StackOverflow)
I'm curious about the differences between calling a Func directly vs using Invoke() on it. Is there a difference ? Is the first, syntactical sugar, and calls Invoke() underneath anyway ?
public T DoWork<T>(Func<T> method)
{
return (T)method.Invoke();
}
vs
public T DoWork<T>(Func<T> method)
{
return (T)method();
}
Or am I on the wrong track entirely :) Thanks.
Source: (StackOverflow)
I have a scenario. (Windows Forms, C#, .NET)
- There is a main form which hosts some user control.
- The user control does some heavy data operation, such that if I directly call the
UserControl_Load
method the UI become nonresponsive for the duration for load method execution.
- To overcome this I load data on different thread (trying to change existing code as little as I can)
- I used a background worker thread which will be loading the data and when done will notify the application that it has done its work.
- Now came a real problem. All the UI (main form and its child usercontrols) was created on the primary main thread. In the LOAD method of the usercontrol I'm fetching data based on the values of some control (like textbox) on userControl.
The pseudocode would look like this:
CODE 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.
}
}
The Exception it gave was
Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on.
To know more about this I did some googling and a suggestion came up like using the following code
CODE 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 variable List<string> which will be binded to grid at some later stage
}
}
BUT BUT BUT... it seems I'm back to square one. The Application again
become nonresponsive. It seems to be due to the execution of line #1 if condition. The loading task is again done by the parent thread and not the third that I spawned.
I don't know whether I perceived this right or wrong. I'm new to threading.
How do I resolve this and also what is the effect of execution of Line#1 if block?
The situation is this: I want to load data into a global variable based on the value of a control. I don't want to change the value of a control from the child thread. I'm not going to do it ever from a child thread.
So only accessing the value so that the corresponding data can be fetched from the database.
Source: (StackOverflow)
I am only somewhat familiar with multi-threading in that I've read about it but have never used it in practice.
I have a project that uses a third party library that shares the status of an input device by raising events. The problem is, the way the library is written these events are raised from a different thread.
My application does not need to be multi-threaded and I've run into a lot of classic threading issues (UI controls complaining about being interacted with from a different thread, collections that get modified as one piece of code is iterating over it, etc.).
I just want the 3rd party library's event to be given back to my UI thread. Specifically what I think should happen is:
My class receives the event and the handler is being run on a different thread than the UI. I want to detect this condition (like with InvokeRequired), and then perform the equivalent of BeginInvoke to give control back to the UI thread. Then the proper notifications can be sent on up the class hierarchy and all of my data is only touched by the one thread.
The problem is, the class that is receiving these input events is not derived from Control and therefore doesn't have InvokeRequired or BeginInvoke. The reason for this is that I tried to cleanly separate UI and the underlying logic. The class is still being run on the UI thread, it just doesn't have any UI inside the class itself.
Right now I fixed the issue by ruining that separation. I pass in a reference to the control that will be displaying data from my class and using its Invoke methods. That seems like it defeats the whole purpose of separating them because now the underlying class has a direct dependence on my specific UI class.
Perhaps there's a way to save a reference to the thread that ran the constructor and then there's something in the Threading namespace that will perform the Invoke commands?
Is there a way around this? Is my approach completely wrong?
Source: (StackOverflow)
Update: I've filed a bug report on Microsoft Connect: https://connect.microsoft.com/VisualStudio/feedback/details/568271/debugger-halting-on-exception-thrown-inside-methodinfo-invoke#details
If you can reproduce this problem on your machine, please upvote the bug so it can be fixed!
Ok I've done some testing and I've reduced the problem to something very simple:
i. Create a method in a new class that throws an exception:
public class Class1 {
public void CallMe() {
string blah = null;
blah.ToLower();
}
}
ii. Create a MethodInfo that points to this method somewhere else:
Type class1 = typeof( Class1 );
Class1 obj = new Class1();
MethodInfo method = class1.GetMethod( "CallMe" );
iii. Wrap a call to Invoke() in a try/catch block:
try {
method.Invoke( obj, null ); // exception is not being caught!
} catch {
}
iv. Run the program without the debugger (works fine).
v. Now run the program with the debugger. The debugger will halt the program when the exception occurs, even though it's wrapped in a catch handler that tries to ignore it. (Even if you put a breakpoint in the catch block it will halt before it reaches it!)
In fact, the exception is happening when you run it without the debugger too. In a simple test project it's getting ignored at some other level, but if your app has any kind of global exception handling, it will get triggered there as well. [see comments]
This is causing me a real headache because it keeps triggering my app's crash-handler, not to mention the pain it is to attempt to debug.
Source: (StackOverflow)
I have a somewhat complex WPF application which seems to be 'hanging' or getting stuck in a Wait call when trying to use the dispatcher to invoke a call on the UI thread.
The general process is:
- Handle the click event on a button
- Create a new thread (STA) which: creates a new instance of the presenter and UI, then calls the method Disconnect
- Disconnect then sets a property on the UI called Name
- The setter for Name then uses the following code to set the property:
if(this.Dispatcher.Thread != Thread.CurrentThread)
{
this.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate{
this.Name = value; // Call same setter, but on the UI thread
});
return;
}
SetValue(nameProperty, value); // I have also tried a member variable and setting the textbox.text property directly.
My problem is that when the dispatcher invoke method is called it seems to hang every single time, and the callstack indicates that its in a sleep, wait or join within the Invoke implementation.
So, is there something I am doing wrong which I am missing, obvious or not, or is there a better way of calling across to the UI thread to set this property (and others)?
Edit: The solution was to call System.Windows.Threading.Dispatcher.Run() at the end of the thread delegate (e.g. where the work was being performed) - Thanks to all who helped.
Source: (StackOverflow)
I'm currently working on a project where a section of the code looks like this:
Select Case oReader.Name
Case "NameExample1"
Me.Elements.NameExample1.Value = oReader.ReadString
....
Case "NameExampleN"
Me.Elements.NameExampleN.Value = oReader.ReadString
....
End Select
It continues on for a while. The code is obviously verbose and it feels like it could be improved. Is there any way to dynamically invoke a property in VB.NET such that something like this can be done:
Dim sReadString As String = oReader.ReadString
Me.Elements.InvokeProperty(sReadString).Value = sReadString
Source: (StackOverflow)
I have the following code in my worker thread (ImageListView
below is derived from Control
):
if (mImageListView != null &&
mImageListView.IsHandleCreated &&
!mImageListView.IsDisposed)
{
if (mImageListView.InvokeRequired)
mImageListView.Invoke(
new RefreshDelegateInternal(mImageListView.RefreshInternal));
else
mImageListView.RefreshInternal();
}
However, I get an ObjectDisposedException
sometimes with the Invoke
method above. It appears that the control can be disposed between the time I check IsDisposed
and I call Invoke
. How can I avoid that?
Source: (StackOverflow)
I am a novice programmer so I could be completely mistaken here, but this issue bugs me more then it should.
This is actually a follow-up from this question.
The accepted answer was, that you have to call InvokeRequired in order to avoid some overhead, because there is a chance you are already operating on the UI thread.
In theory, I agree that it could save some time. After some tests I found out that using Invoke takes about twice the time compared to calling an operation normally (tests like setting the text of a label n times, or placing a very, very big string in a RichTextBox).
But! Then there is practice.
MSDN documentation says:
This property can be used to determine if you must call an invoke method, which can be useful if you do not know what thread owns a control.
In most cases, you do know when you try to access a control from another thread. Actually the only situation I can think of is, when the control is accessed from a method that can be called by thread X aswell as the owner thread. And that to me is a very unlikely situation.
And even if you genuinely don't know which thread tries to manipulate the control, there is the fact that the UI thread doesn't have to be updated that frequently. Anything between 25-30 fps should be okay for your GUI. And most of the changes made in the UI-controls takes far less then milliseconds to perform.
So if I understand corrrectly, the only scenario where you have to check if an invoke is required is when you don't know which thread is accessing the control and when the GUI update takes more than about 40 ms to finish.
Then there is the answer to this question I asked on http://programmers.stackexchange.com. Which states that you shouldn't be busy with premature optimisation when you don't need it. Especially if it sacrifices code readability.
So this brings me to my question: shouldn't you just use invoke when you know a different thread accesses a control, and only when you know your UI thread can access that piece of code and you find that it should run faster, that you should check if an Invoke is required?
PS: after proofreading my question it really sounds like I am ranting. But actually I am just curious why InvokeRequired is seemingly overused by many more-experienced-than-me programmers.
Source: (StackOverflow)
This question already has an answer here:
I have a list of commands (i, h, t, etc) that the user will be entering on a command line/terminal Java program. I would like to store a hash of command/method pairs:
'h', showHelp()
't', teleport()
So that I can have code something like:
HashMap cmdList = new HashMap();
cmdList.put('h', showHelp());
if(!cmdList.containsKey('h'))
System.out.print("No such command.")
else
cmdList.getValue('h') // This should run showHelp().
Is this possible? If not, what is an easy way to this?
Source: (StackOverflow)
I've this little method which is supposed to be thread safe. Everything works till i want it to have return value instead of void. How do i get the return value when BeginInvoke is called?
public static string readControlText(Control varControl) {
if (varControl.InvokeRequired) {
varControl.BeginInvoke(new MethodInvoker(() => readControlText(varControl)));
} else {
string varText = varControl.Text;
return varText;
}
}
Edit: I guess having BeginInvoke is not nessecary in this case as i need value from GUI before the thread can continue. So using Invoke is good as well. Just no clue how to use it in following example to return value.
private delegate string ControlTextRead(Control varControl);
public static string readControlText(Control varControl) {
if (varControl.InvokeRequired) {
varControl.Invoke(new ControlTextRead(readControlText), new object[] {varControl});
} else {
string varText = varControl.Text;
return varText;
}
}
But not sure how to get value using that code either ;)
Source: (StackOverflow)