[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 462
  • Last Modified:

how make callback method in C#

Hi expert

Currently I am developing one application
I want to call user thread from worker thread.
for that i need callback function for UI updation.
how i can i do this .

Thanks in advance
0
avinash_takale
Asked:
avinash_takale
2 Solutions
 
ThaloxCommented:

you can do this by using delegates.

have a look at

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemDelegateClassTopic.asp

or simply type delegate in your visual studio and press F1

hope that helps,

Thalox
0
 
muskokCommented:
1) define a delegate with the same signature as your method that will update UI
2) In worker thread create a new delegate of this type
3) use Control.Invoke to invoke the delegate in Main Thread

Note: The thread method must reach at least one member control (may be a form) to invoke the method.

Sample:
//Assume we have a text box named "m_txtMessage"

//Delegate that will be used to call the method
public delegate void MyUpdaterHandler(string newText);

private void UpdateUI(string newText)
{
  m_txtMessage.Text = newText;
}

//Your worker thread method
private void WorkerThreadMethod()
{
  //Do something in different thread
  //.....
 
  //Create a new delegate
  MyUpdaterHandler  _dlg = new MyUpdaterHandler(this.UpdateUI);

  //Invoke delegate in the thread whic created the control   txtMessage (which is Main Thread) you can also use main form instance
 
 txtMessage.Invoke(dlg, new object[]{ "Text updated in Main Thread" });
}

//UpdateUI()  method will be called on the thread that created the control "txtMessage"
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now