GoozMeister
GoozMeister

Reputation: 355

Getting error The type arguments for method '......' cannot be inferred from the usage

i am currently trying to use the method bellow in my async Task but im getting the error when im trying to use the StartSTATask:

The type arguments for method 'PrintService.StartSTATask(Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

This is the StartSTATask method

private Task<T> StartSTATask<T>(Func<T> func)
        {
            var tcs = new TaskCompletionSource<T>();
            Thread thread = new Thread(() =>
            {
                try
                {
                    tcs.SetResult(func());
                }
                catch (Exception e1)
                {
                    tcs.SetException(e1);
                }
            });
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            return tcs.Task;
        }

this is where i try to use StartSTATask:

public async Task printLabelEindcontroleAsync(LabelEindControleDto label)
        { 
            await StartSTATask(() => {

                var config = new MapperConfiguration(cfg => cfg.CreateMap<LabelEindControleDto, LabelEindcontrole>());
                var mapper = new Mapper(config);
                LabelEindcontrole labelEindcontrole = mapper.Map<LabelEindcontrole>(label);

                new SuplaconPrint.Queries.LabelEindcontrole(labelEindcontrole);
            });
        }

Upvotes: 0

Views: 1604

Answers (1)

TheGeneral
TheGeneral

Reputation: 81583

You are not returning anything. Therefore, it can't infer how you want to use the generic parameter and returning type of StartSTATask in the lambda .

The following would work, as it can infer the types, in this case an int

await StartSTATask(
        () =>
           {
              return 0; // example
           });

I am guessing you'd also want a variant without a generic type (for such an occasion)

private Task StartSTATask(Action action)
{
   var tcs = new TaskCompletionSource<object>();
   Thread thread = new Thread(() =>
                                 {
                                    try
                                    {
                                       action();
                                       tcs.SetResult(null);
                                    }
                                    catch (Exception e1)
                                    {
                                       tcs.SetException(e1);
                                    }
                                 });
   thread.SetApartmentState(ApartmentState.STA);
   thread.Start();
   return tcs.Task;
}

For which this would compile and work

await StartSTATask(
        () =>
           {
                //
           });

Upvotes: 2

Related Questions