Link to home
Start Free TrialLog in
Avatar of axnst2
axnst2Flag for United States of America

asked on

An Action (callback) with parameters and return value

Hi Experts,

How would I go about creating/using an Action (callback) with parameters and return value.

So here's what I am trying to accomplish:

I have a UI exe and a DLL that performs syncing operations in a background thread.  Every now and again the syncing thread needs input from the user.  What I am thinking about doing, is when the UI instantiates the background thread, it would pass it a function pointer/Action (pointing to one of the UI’s functions that would pop up a message box for the user).  Then from that point on, any time the syncing thread needs to interact with the user, it’ll use this callback function to interact with the user.  The user would click Yes/No and then that would be returned to the thread and the read would zig or zag based on the user’s input.  How would the Action declaration look like for this and how would the class constructor (accepting the function pointer) look like?

I am thinking something like this but I know I’m missing the return value:

(Please ignore the simplification of the thread part)

public class SyncerClass
{
     private Action<MyParameterClass> _useMessageCallback;

     public SyncerClass(Action<MyParameterClass> useMessageCallback)
     {
          _useMessageCallback = useMessageCallback;
          Thread.StartThread(WorkerThread);
     }

     WorkerThread()
     {
      while(true)
      {
                         MyParameterClass parameter = new MyParameterClass();
                         arameter.Message = “Would you like me to Zig instead of Zag?”;

                         if(_useMessageCallback(parameter) == DialogResult.Yes)
                         {
                              //Zig
                         }
                         else
                         {
                              //Zag
                         }
               }
     }
}

Thank you!
ASKER CERTIFIED SOLUTION
Avatar of p_davis
p_davis

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of axnst2

ASKER

With func it worked!  Thanks!

Why would you prefer the delegate and what would the delegate prototype look like?
Avatar of axnst2

ASKER

delegate TResult MyDelegate(T)?
Avatar of p_davis
p_davis

Its just a preference of mine... if func suites you, use it.
func actually is a delegate too, anyway
Avatar of axnst2

ASKER

Thank you!

I ended up using this:

Func<UIMessageParameters, DialogResult> _displayUserMessage;