线程不能正常工作,c#
本文关键字:工作 不能 常工作 线程 | 更新日期: 2023-09-27 18:09:40
我最近一直在尝试使用多线程来加速我的代码,但它一直不太好。
我在我目前正在开发的代码中有这个简单的逻辑:
Start Main Code
{
//code
Thread thread1 = new Thread(() => {list1 = Method1();});
thread1.Start();
Thread thread2 = new Thread(() => {list2 = Method2();});
thread2.Start();
//more code
thread1.Join();
ListA = list1;
thread2.Join();
ListB = list2;
return whatever;
}
我希望thread1和thread2与主代码一起运行,然后在Join()处相遇,但由于某种原因,我的代码似乎随机地跳过并到达返回语句,甚至没有遍历整个主代码。
我在这里错过了什么吗?
编辑:我很抱歉我的问题没有说清楚。我的意思是:代码如预期的那样从第1行开始,然后正常运行,直到满足我声明的Thread.Start()。然后它继续正常运行几行,直到它突然跳到主代码块末尾的"return whatever"行。
我知道在调试这类代码时,它会跳过我创建的所有方法,这不是我面临的问题。正如我所提到的,问题在于突然跳转到代码的末尾。
我使用的是。net Framework 4.5.1
由于您没有指定。net框架的哪个版本,我将假设您可以使用异步框架。如果需要,此代码将并行运行两个任务,并且应该只占用您拥有的最长的任务。而不是Task.Delay()
,你会有你自己的代码,实际上去数据库和检索数据。
(下面代码的运行版本https://dotnetfiddle.net/CCCfKw)
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
public class Program
{
public static void Main()
{
var doWork = new SomeWorkClass();
var list1Task = doWork.GetList1Async();
var list2Task = doWork.GetList2Async();
var list1 = list1Task.Result;
var list2 = list2Task.Result;
var newList = list1.Concat(list2).ToList();
foreach(var str in newList) {
Console.WriteLine(str);
}
}
}
public class SomeWorkClass
{
private List<string> _list1 = new List<string>() { "Some text 1", "Some other text 2" };
private List<string> _list2 = new List<string>() { "Yet more text 3" };
public async Task<List<string>> GetList1Async()
{
await Task.Delay(1000);
return _list1;
}
public async Task<List<string>> GetList2Async()
{
await Task.Delay(700);
return _list2;
}
}