Azure Function V1 with WPF Controls

162 Views Asked by At

I tried to use Azure function v1 that contains some WPF controls. while Azure funtion v1 supports .Net framework, and it is supposed to work with windows environment. whenever the debugger reaches the WPF control, exception is being thrown shows that

"InvalidOperationException: The calling thread must be STA, because many UI components require this. "

This is how my code looks like, I tested the function within browser.

 [FunctionName("Report1")]
 public static async Task<HttpResponseMessage> RunReport([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "hash/{hash1}")]HttpRequestMessage req, string hash1, TraceWriter log, Microsoft.Azure.WebJobs.ExecutionContext context){}
2

There are 2 best solutions below

1
On BEST ANSWER

Dont have this usage method, Azure Function does not support UI. WPF controls should not be handled in Azure Functions.

0
On

I came all the way back to this answer because I knew it wasn't true. I was already using WPF apps in v1. However I could not get them to work with v4/NET6. I kept running into either deployment issues or error "The specified version of Microsoft.NetCore.App or Microsoft.AspNetCore.App was not found. Microsoft.AspNetCore.App"

I spent 3 days troubleshooting, but then found an app that was working in production. So I just copied the files..

This is what I do

  1. Create WPF .Net Core project with App.Xaml, etc. Do your WPF Stuff there..

  2. Create an Azure Function with these settings

 <PropertyGroup>
    <TargetFramework>net6.0-windows</TargetFramework>
    <AzureFunctionsVersion>v4</AzureFunctionsVersion>
    <OutputType>WinExe</OutputType>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <UseWPF>true</UseWPF>
 </PropertyGroup>

Call and test your WPF function, then before publishing, change WPF App signature to this

<PropertyGroup>
    <OutputType>Library</OutputType>
    <TargetFramework>net6.0-windows</TargetFramework>
    <Nullable>enable</Nullable>
    <UseWPF>true</UseWPF>
    <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>

Finally in the function itself, must run as STA Thread

 var t = new System.Threading.Thread(() =>
  {
      XamlProject j = new XamlProject;
      finalResult = j.DoSomething();
  });
  t.SetApartmentState(System.Threading.ApartmentState.STA);
  t.Start();
  t.Join();

This works for me, but may have something to do with the Azure.Functions.Worker.Sdk or the fact that you can reference a class library, but not executable, im not sure but these are working in .Net Core with STA Thread in Azure Function v4/Net6

Try to avoid doing any async stuff inside STA Thread unless you want to build your own thread synchronization routines. Do async stuff and pass objects into thread instead.