如果您能告诉我关于多次异步调用同一方法的意见,我将不胜感激。我更感兴趣的是了解这项活动的安全方面。我在这里发布了一个控制台代码,其中包含一个我异步调用四次的方法,它运行良好。到目前为止,我还没有注意到任何问题。但我想确定。请输入以下代码:
public class OneMethodCalledServeralTimes
{
protected async Task<bool> DoSomeWork(Values values, int whenItIsCalled, string description)
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
await Task.Delay(values.Value);
Console.WriteLine("{0} Completed in {1} and this was called: {2}",description, stopWatch.ElapsedMilliseconds, whenItIsCalled);
return true;
}
public bool DoAllWork()
{
Console.WriteLine("=====================Started doing weekend Chores===================");
var task1 = DoSomeWork(new Values { Value = 10000 }, 1, "First work to be done");
var task2 = DoSomeWork(new Values {Value = 7000}, 1, "First work to be done");
var task3 = DoSomeWork(new Values { Value = 4000 }, 2, "second work to be done");
var task4 = DoSomeWork(new Values { Value = 1000 }, 3, "third work to be done");
Task.WaitAll(task1, task2, task3, task4);
Console.WriteLine("=====================Completed doing weekend Chores===================");
return true;
}
}
以下是调用上述调用的控制台应用程序:
static void Main(string[] args)
{
//var weekend = new HomeWork().DoAllWork();
Console.WriteLine("############################Using proper methods#############################");
var workToBeDone= new OneMethodCalledServeralTimes().DoAllWork(); //Passing parameters and the most successful one
Console.WriteLine("It took the entire four mothod {0} seconds to finish", stopewach.ElapsedMilliseconds/1000.0);
Console.ReadKey();
}
我也非常欢迎任何关于多次异步调用相同方法的缺点和优点的简明观点