0

I have some window workflows which use some .net assemblies. I am accessing some hardware from these workflow windows. My XYZ services which are being published on IIS through virtual directory method help this all. Now I want to consume these workflows from my .Net web Application. I made a wcf service and a web client. my wcf service (on web client request) load the workflows (Success) and try to Execute.

The Problem is when I Call the execution of the loaded workflow, It gives the exception "The calling thread must be STA, because many UI components require this."

2 Answers2

2

If you're using WinForms/WPF objects from a thread that is not a single-thread apartment thread you'll get this exception. In order to use those objects from your WCF Service you need to create a new thread, set the apartment state on that thread to STA and then start the thread.

My trivial example takes a string and checks it against a WPF TextBox's SpellCheck feature:

public bool ValidatePassword(string password)
{
    bool isValid = false;

    if (string.IsNullOrEmpty(password) == false)
    {
        Thread t = new Thread(() =>
        {
            System.Windows.Controls.TextBox tbWPFTextBox = new System.Windows.Controls.TextBox();

            tbWPFTextBox.SpellCheck.IsEnabled = true;
            tbWPFTextBox.Text = password;
            tbWPFTextBox.GetNextSpellingErrorCharacterIndex(0, System.Windows.Documents.LogicalDirection.Forward);

            int spellingErrorIndex = tbWPFTextBox.GetNextSpellingErrorCharacterIndex(0, System.Windows.Documents.LogicalDirection.Forward);

            if (spellingErrorIndex == -1)
            {
                isValid = true;
            }
            else
            {
                isValid = false;
            }

        });

        t.SetApartmentState(ApartmentState.STA);
        t.Start();
        t.Join();
    }

    return isValid;
}

You can also reference this S.O. post: How to make a WCF service STA (single-threaded)

As well as the link in the answer: http://www.netfxharmonics.com/2009/07/Accessing-WPF-Generated-Images-Via-WCF

Community
  • 1
  • 1
Aaron
  • 7,055
  • 2
  • 38
  • 53
0

I found this

STAthread

Also you can solve your problem using

[STAthread]
private void yourMethod()
{
//Call the execution here
}

Or well try to do this:

private void yourMethod()
{
     Thread t = new Thread(here delegate your method where you call the execution);
     t.SetApartmentState(ApartmentState.STA);
     t.Start();
}