Task t = Task.Run(() => MyMethod());
t.Wait();
If so, can you provide some example code that does this?using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EE_Q29170256
{
class Program
{
static void Main(string[] args)
{
var tasks = new List<Task<int>>(from i in Enumerable.Range(0, 5) select Task.Run(() =>
{
Task.Delay(1000);
return i;
}));
Task.WaitAll(tasks.ToArray());
foreach(var task in tasks)
{
Console.WriteLine($"Task {task.Id} resulted in {task.Result}");
}
Console.ReadLine();
}
}
}
Which produces the following output -Task t = MyMethod();
t.Wait();
I'm trying to determine if inlining can also happen if I first call Task.Run().
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace ThreadConsoleApp6
{
class Program
{
static void Main(string[] args)
{
ShowMaxThreads();
ShowAvailableThreads();
bool stat = ThreadPool.SetMaxThreads(8, 8);
ShowAvailableThreads();
var tasks = new List<Task>();
for (int i = 0; i < 8; ++i)
{
tasks.Add(Task.Run(() => Wait5Seconds()));
}
Thread.Sleep(1000);
ShowAvailableThreads();
Thread thread = Thread.CurrentThread;
int threadId = thread.ManagedThreadId;
Console.WriteLine("Main Thread: {0:N0}", threadId);
Console.WriteLine("Main thread is available. Let's run AnotherTask()");
Task t = Task.Run(() => AnotherTask());
t.Wait(); // We're waiting. Why does it not inline task and run it on main thread?
Task.WaitAll(tasks.ToArray());
Console.WriteLine("Press any key");
Console.ReadKey();
}
static private void AnotherTask()
{
Thread thread = Thread.CurrentThread;
int threadId = thread.ManagedThreadId;
Console.WriteLine("Another Task Thread: {0:N0}", threadId);
}
static void Wait5Seconds()
{
Thread.Sleep(5000);
}
static private void ShowMaxThreads()
{
int workerThreads;
int portThreads;
ThreadPool.GetMaxThreads(out workerThreads, out portThreads);
Console.WriteLine("\nMaximum worker threads: \t{0}\nMaximum completion port threads: {1}", workerThreads, portThreads);
}
static private void ShowAvailableThreads()
{
int workerThreads;
int portThreads;
ThreadPool.GetAvailableThreads(out workerThreads, out portThreads);
Console.WriteLine("\nAvailable worker threads: \t{0}\nAvailable completion port threads: {1}\n", workerThreads, portThreads);
}
}
}
I set max threads to 8 because that's the minimum I can for my machine. I then spin off 8 tasks so there are no more available ThreadPool threads. I then try to get AnotherTask() to be inlined, but it insists on waiting instead.
Why are you calling ThreadPool.SetMaxThreads(8