WCF: Accessing a Window Form from Inside a Service

How can I achieve this scenario?

I have a WCF service hosted on a Windows Form, and whenever the service client calls a method on the service, I want the service to be able to write a message to the textbox on the window form.

I thought I would make my WCF service a singleton, submit my form using an interface that the form implements to the service, and then save that instance. then when the client calls the service, I can just use the form instance to write to the textbox.

I cannot do this, of course, as I cannot submit the form to the WCF service.

Any ideas or code examples?

+2


source to share


2 answers


The service instance and your Windows Form run on two separate threads, and you cannot simply update the UI element on the main UI thread from the service instance.

You need to use a sync context and delegate to properly and safely update the UI from the service thread.

See this CodeProject article - in the middle, the author talks about "problems with UI threads". This is basically what you need to do:

SendOrPostCallback callback = 
    delegate (object state)
    {   
        yourListBox.Add(state.ToString());
    };

_uiSyncContext.Post(callback, guestName);

      



See Juval Lowy MSDN article " WCF Synchronization Contexts " for a comprehensive introduction to the topic.

Hosting a WCF service inside a Winforms application seems like a pretty bad idea to me - first of all because of all these threading issues, and second, it will only work if the winforms application is running. Could you please put your WCF service in a console application or Windows NT service and then just create a Winforms based monitoring application that can inspect for example. database table for incoming messages or something else?

Mark

+2


source


Check out this SO answer - as far as I understand it is basically the same question.



You can inject dependencies into WCF services: you just need to implement a custom ServiceHostFactory that lays everything out for you.

+1


source







All Articles