Rob C
Rob C

Reputation: 117

Conversion of code from vb.net to c#- await task

I have been using the following line of code happily for a while now and it seems to do the job satisfactorily. I am looking to convert it to C#. I am trying to convert:

Dim result as string = Await Task(Of String).Factory.StartNew(Function() MyClass.PerformJob(param1,param2,param3))

I am entering the following code in C# :

string result = await Task<string>.Factory.StartNew((Func<string>) MyClass.PerformJob((param1,param2,param3));

This generates the following error:

'Cannot convert type 'string' to 'System.Func<string>' 

I assume this is related to passing parameters in the way I am; I'm lost as to why this should work in VB.NET and not C#?

Many thanks for your help.

Upvotes: 2

Views: 810

Answers (4)

Dave Doknjas
Dave Doknjas

Reputation: 6542

You have to replace 'MyClass' with 'this' - C# doesn't have a strict equivalent to 'MyClass':

string result = await Task<string>.Factory.StartNew(() => this.PerformJob(param1,param2,param3));

Upvotes: 1

ventaur
ventaur

Reputation: 1851

You don't need to cast it to Func, and you likely need to use a lambda to get your parameters into the PerformJob call. Try this.

string result = await Task<string>.Factory.StartNew(() => MyClass.PerformJob(param1,param2,param3));

Upvotes: 1

RePierre
RePierre

Reputation: 9576

You are trying to cast the result of MyClass.PerformJob method to Func<string> when the result is of type string. Use this:

string result = await Task<string>.Factory
    .StartNew(() => MyClass.PerformJob(param1,param2,param3));

Upvotes: 1

sa_ddam213
sa_ddam213

Reputation: 43636

Assuming PerformJob is a Func<string> I dont think you need the Func<string> cast.

string result = await Task<string>.Factory.StartNew(MyClass.PerformJob(param1,param2,param3));

Upvotes: 0

Related Questions