0

I'm a C# newer and trying to develop a C# Library. My API is async and will callback to the user. I want the callback function will execute in the UI thread because I think this is convenient to the user.

public void ApiAsync(EventHandler<MyArgs> completedHandler);

If WPF, I can use Dispatcher.Invoke(), in WindowsForm, maybe another method. But what confused me now is that whether my SDK should do this or just callback in the worker thread and SDK don't care the UI thread and let the user control themselves. Realy appreciate anyone helps me, thanks.

Jayden
  • 11
  • 2
  • See marked duplicate for literal answer to your question. But, note that unless your class is _specifically_ for the purpose of managing cross-thread invocations, it is likely _not_ appropriate for your library to attempt to do this at all. Depending on the callback, it may be more appropriate to expose the result via an awaitable `async` method, or to have the caller pass you a `Progress` object (as an `IProgress` type), either of which will handle returning the UI thread automatically. Note also in WPF, if the client uses view model binding, WPF will automatically handle cross-thread. – Peter Duniho Sep 20 '17 at 06:10
  • See also e.g. https://stackoverflow.com/questions/1149402/how-to-detect-if-were-on-a-ui-thread, https://stackoverflow.com/questions/23397496/c-sharp-wpf-updating-the-ui-from-another-thread-created-within-another-class, and https://stackoverflow.com/questions/10981574/capturing-the-main-thread-synchronizationcontext-or-dispatcher-from-a-library – Peter Duniho Sep 20 '17 at 06:13
  • @PeterDuniho, thanks a lot. My library should be compatibility with .net3.5, so can't use awaitable. Can I ask one more question? In my sdk, I would authenticate to a server using OAUTH2, and in this procedure, the server will return a URL let the user to input username and password, my question is who will call the browser, sdk or sdk user? – Jayden Sep 20 '17 at 06:42
  • That's a matter of opinion and will depend somewhat on the rest of the design. But absent any other information, I would leave that task up to the component handling the UI, i.e. the "sdk user" if I understand your comment correctly. The library can return the URL and let the UI component present the login using whatever means it deems appropriate (I suppose it might even bypass display of the web page if it really wanted to, redirecting user input as it sees fit from an alternate UI). This kind of "separation of concerns" and "decoupling" provides the best flexibility. – Peter Duniho Sep 20 '17 at 07:13
  • @PeterDuniho, Thanks very much – Jayden Sep 20 '17 at 07:21

0 Answers0