Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task does not contain a definition for Run method

I tried to implement multithreading in my code, 1st time. When i tried to use

Task T = Task.Run(() => { });

Visual Studio is still underlines Run() with statement "Task does not contain a definition 'Run' "

I'm using System.Threading.Tasks; Internet knows nothing about this problem

like image 973
kifu Avatar asked Jan 20 '18 20:01

kifu


People also ask

What is Task run ()?

The Run method allows you to create and execute a task in a single method call and is a simpler alternative to the StartNew method. It creates a task with the following default values: Its cancellation token is CancellationToken.

What is Task method in C#?

A task in C# is used to implement Task-based Asynchronous Programming and was introduced with the . NET Framework 4. The Task object is typically executed asynchronously on a thread pool thread rather than synchronously on the main thread of the application.

What is the difference between Task and thread?

Differences Between Task And ThreadThe Thread class is used for creating and manipulating a thread in Windows. A Task represents some asynchronous operation and is part of the Task Parallel Library, a set of APIs for running tasks asynchronously and in parallel. The task can return a result.

How do you end a Task in C#?

Cancel(); Console. WriteLine("\n\nPress any key to stop the task"); Console.


2 Answers

.NET 4.0 does not have a Task.Run method. Instead you can use:

Task T = Task.Factory.StartNew(() => { });

Which you can learn more about here

like image 99
Michael Hancock Avatar answered Sep 22 '22 13:09

Michael Hancock


Task.Run was introduced in .NET 4.5, you are using .net 4.0. If you can't upgrade your project you can include the Microsoft.Bcl.Async NuGet package to introduce a TaskEx.Run( to add it in to .net 4.0.

like image 43
Scott Chamberlain Avatar answered Sep 24 '22 13:09

Scott Chamberlain