C
C#2y ago
2fur

How can I start the task by string?

I need something like this, is this possible to do? void Main() { var input = Console.ReadLine(); Task.Run(() => input ); }
9 Replies
Becquerel
Becquerel2y ago
what would this do?
2fur
2fur2y ago
start a task by it's name(string input from user)
Becquerel
Becquerel2y ago
tasks don't have names if i typed in "hello", in that example, what would you expect to happen
2fur
2fur2y ago
If I type "ping" - start task ping
Becquerel
Becquerel2y ago
ok, that's a method called ping, not a task i would suggest something like this
var dictionary = new Dictionary<string, Func<Task>>()
{
{ "ping", () => ping() },
{ "blah", () => otherMethod() },
};

var userInput = Console.ReadLine();

if (dictionary.TryGetValue(userInput, out var action))
{
var task = action.Invoke();
await task;
}
else
{
Console.WriteLine("no method found");
}
var dictionary = new Dictionary<string, Func<Task>>()
{
{ "ping", () => ping() },
{ "blah", () => otherMethod() },
};

var userInput = Console.ReadLine();

if (dictionary.TryGetValue(userInput, out var action))
{
var task = action.Invoke();
await task;
}
else
{
Console.WriteLine("no method found");
}
2fur
2fur2y ago
okay, I will try it thx :)
Becquerel
Becquerel2y ago
dogeburger3
2fur
2fur2y ago
That's work. Thank you so much
Becquerel
Becquerel2y ago
swagyes