In a plugin I'm creating in C# with .NET 4.0 for an existing third-party application, I created a thread to have a service listen on a named pipe.
In the function that I set as the OperationContract
, I need to to call functions that deal with the UI, which sometimes create new UI controls downstream after they are called. Namely I get the following error:
"Controls created on one thread cannot be parented to a control on a different thread"
I figured out that I should use a BeginInvoke
from the OperationContract
function to access the UI, but my problem is that I do not know from where I do get the object from which to call. I tried quite a few (this.BeginInvoke
, Application.Current.BeginInkove
) but have not been able to figure it out, so I'm not able to even compile it.
The code below is the schema of the service that is created from a thread different from the main UI thread. I need to know how to call BeginInvoke to run some code from the main UI thread from the function called OperationContractForService(string value):
using System;
using System.Windows;
using System.Windows.Forms;
using System.ServiceModel;
using System.Threading;
.
.
.
[ServiceContract]
public interface IInterfaceForService
{
[OperationContract]
string OperationContractForService(string value);
}
public class InterfaceForService : IInterfaceForService
{
public string OperationContractForService(string value)
{
// .
// Some code that may create controls in the UI in the main thread
// How do I call BeginInvoke from here?
// .
}
}
How can this be done?