我的编程方式有什么问题或本质上不安全吗?我仍在学习 .NET 中的线程逻辑。
基本上,我的 APIManager.ExecuteRequest()
被调用了两次,这需要一段时间,所以我希望这两个调用同时发生。看起来 dataResult 变量在连接后都被适本地填充了,但我一直看到关于 AsyncResult
和所有这些其他 .NET 并发相关 API 的事情,我认为我可能过于简单化了一点。
如果没有任何问题,有人可以告诉我获得相同结果的更好方法吗?
MyDataResult dataResult1 = null, dataResult2 = null;
System.Threading.Thread t1 = new System.Threading.Thread(delegate()
{
dataResult1 = APIManager.ExecuteRequest(dataRequest1, TBIdentifiers.Text, TBCommands.Lines);
});
System.Threading.Thread t2 = new System.Threading.Thread(delegate()
{
dataResult2 = APIManager.ExecuteRequest(dataRequest2, TBIdentifiers.Text, TBCommands.Lines);
});
t1.Start();
t2.Start();
t1.Join();
t2.Join();
最佳答案
这看起来不错。 也许您可以通过在当前线程中运行第二个请求来稍微优化一下,而不是让 3 个线程中一个只等待另外两个:
System.Threading.Thread t1 = new System.Threading.Thread(() =>dataResult1 = APIManager.ExecuteRequest(dataRequest1, TBIdentifiers.Text, TBCommands.Lines));
t1.Start();
dataResult2 = APIManager.ExecuteRequest(dataRequest2, TBIdentifiers.Text, TBCommands.Lines);
t1.Join();
关于c# - .NET 线程 - 这是处理返回结果的两个线程的合适方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11294215/