C# 创建新任务没有运行整个方法

C# 创建新任务没有运行整个方法,c#,asp.net-core,.net-core,task,task-parallel-library,C#,Asp.net Core,.net Core,Task,Task Parallel Library,我有一个计算,I/O我想发送到另一个线程,因此在网站上,用户可以转到下一页,而无需等待计算完成。据我所知,我需要做的是像这样调用方法 var backgroundTask=Task.Run(()=>CalculateSet(uow、profile、userId、specialtyCode)) 但是当我这样做的时候,似乎调用了方法中的一行,然后就消失了。。没有一部分工作完成了 我错过什么了吗 [Fact] public void Calculation_Xls() {

我有一个计算,I/O我想发送到另一个线程,因此在网站上,用户可以转到下一页,而无需等待计算完成。据我所知,我需要做的是像这样调用方法

var backgroundTask=Task.Run(()=>CalculateSet(uow、profile、userId、specialtyCode))

但是当我这样做的时候,似乎调用了方法中的一行,然后就消失了。。没有一部分工作完成了

我错过什么了吗

  [Fact]
    public void Calculation_Xls()
    {
        string currentDirectory = Directory.GetCurrentDirectory();
        string filesDirectory = currentDirectory + "\\Files";
        System.Text.Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

        var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
        Configuration = builder.Build();

        var optionsBuilder = new DbContextOptionsBuilder<RetContext>();
        optionsBuilder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));

        int i = 0; //outer loop

        UnitOfWork uow = new UnitOfWork(new RetContext(optionsBuilder.Options));

        using (var stream = System.IO.File.Open(filesDirectory + "\\t2UserProfileDataTwoUserPerSpecialty.xlsx",
            FileMode.Open, FileAccess.Read))
        {
            using (var reader = ExcelReaderFactory.CreateReader(stream))
            {
                do
                {
                    while (reader.Read())
                    {
                        if (i != 0)
                        {
                            var userId = reader.GetString(0);
                            var specialtyCode = reader.GetString(1);
                            var userProfileElement1_WorkExp = reader.GetValue(2);
                            var userProfileElement2_VolExp = reader.GetValue(3);
                            var userProfileElement3_ResExp = reader.GetValue(4);
                            var userProfileElement4_Pubs = reader.GetValue(5);
                            var userProfileElement5_AOA = reader.GetValue(6);
                            var userProfileElement6_Nspecialties = reader.GetValue(7);
                            var userProfileElement7_PercentApps = reader.GetValue(8);

                            //Create profile
                            UserProfileData profile = new UserProfileData();
                            profile.UserProfileElement1_WorkExp = Convert.ToInt32(userProfileElement1_WorkExp);
                            profile.UserProfileElement2_VolExp = Convert.ToInt32(userProfileElement2_VolExp);
                            profile.UserProfileElement3_ResExp = Convert.ToInt32(userProfileElement3_ResExp);
                            profile.UserProfileElement4_Pubs = Convert.ToInt32(userProfileElement4_Pubs);
                            profile.UserProfileElement5_Aoa = Convert.ToBoolean(userProfileElement5_AOA);
                            profile.UserProfileElement6_Nspecialties = Convert.ToInt32(userProfileElement6_Nspecialties);
                            profile.UserProfileElement7_PercentApps = Convert.ToInt32(userProfileElement7_PercentApps);

                            //Calculate for set of programs. Selects one row at a time from XLS. BulkInsert into DB

                            //THIS ONLY RUNS ONE LINE OF THE METHOD
                             var backgroundTask = Task.Run(() =>  CalculateSet(uow, profile, userId, specialtyCode ));

                            //THIS WORKS
                            //CalculateSet(uow, profile, userId, specialtyCode);
                        }

                        i++;

                        Debug.WriteLine("Bulkcreate complete " + i);


                        //only process xxx rows
                        if (i > 1)
                        {
                            break;
                        }
                    }
                } while (reader.NextResult());
            }
        }

        Debug.WriteLine("Should get here quickly and not wait until task is done");
    }

    private void CalculateSet(UnitOfWork uow, UserProfileData profile, string userId, string specialtyCode)
    {
        //I CAN HIT THIS BREAKPOINT!
        //get specialtyId from code
        var specialtyId = uow.RefMedicalSpecialtyRepository
             .Find(x => x.Code == specialtyCode).FirstOrDefault().Id;

        //NEVER GET TO THIS BREAKPOINT
        //loop through all programs for speciality
        var programsForSpecialty = uow.RefProgramDetailDataRepository
            .Find(x => x.RefMedicalSpecialtyId == specialtyId);

        //List for bulk insert
       // List<UserProgram> userPrograms = new List<UserProgram>();

        //Write a row for each program
        foreach (RefProgramDetailData rpdd in programsForSpecialty.ToList())
        {
            //Get program info
            var programProfile = LoadData.Load_RefProgramProfileData(rpdd.Code);

            //Calculate results
            var userProgram = _calculator.CalculateAll(programProfile, profile, specialtyId, userId);

            //If the Program can not be found in program detail then skip insert
            if (userProgram == null)
            {
                Debug.WriteLine("Program NULL");
            }
            else
            {
                //Write results to UserProgram
                 uow.UserProgramRepository.Create(userProgram);

                //userPrograms.Add(userProgram);

                Debug.WriteLine("Program " + programProfile.ProgramCode);
            }
        }

        //bulk insert
       // uow.UserProgramRepository.BulkCreate(userPrograms);
    }
}
你能试一下吗

[Fact]
        public async Task Calculation_Xls()
        {
            string currentDirectory = Directory.GetCurrentDirectory();
            string filesDirectory = currentDirectory + "\\Files";
            System.Text.Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
            Configuration = builder.Build();

            var optionsBuilder = new DbContextOptionsBuilder<RetContext>();
            optionsBuilder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));

            int i = 0; //outer loop

            UnitOfWork uow = new UnitOfWork(new RetContext(optionsBuilder.Options));

            using (var stream = System.IO.File.Open(filesDirectory + "\\t2UserProfileDataTwoUserPerSpecialty.xlsx",
                FileMode.Open, FileAccess.Read))
            {
                using (var reader = ExcelReaderFactory.CreateReader(stream))
                {
                    do
                    {
                        while (reader.Read())
                        {
                            if (i != 0)
                            {
                                var userId = reader.GetString(0);
                                var specialtyCode = reader.GetString(1);
                                var userProfileElement1_WorkExp = reader.GetValue(2);
                                var userProfileElement2_VolExp = reader.GetValue(3);
                                var userProfileElement3_ResExp = reader.GetValue(4);
                                var userProfileElement4_Pubs = reader.GetValue(5);
                                var userProfileElement5_AOA = reader.GetValue(6);
                                var userProfileElement6_Nspecialties = reader.GetValue(7);
                                var userProfileElement7_PercentApps = reader.GetValue(8);

                                //Create profile
                                UserProfileData profile = new UserProfileData();
                                profile.UserProfileElement1_WorkExp = Convert.ToInt32(userProfileElement1_WorkExp);
                                profile.UserProfileElement2_VolExp = Convert.ToInt32(userProfileElement2_VolExp);
                                profile.UserProfileElement3_ResExp = Convert.ToInt32(userProfileElement3_ResExp);
                                profile.UserProfileElement4_Pubs = Convert.ToInt32(userProfileElement4_Pubs);
                                profile.UserProfileElement5_Aoa = Convert.ToBoolean(userProfileElement5_AOA);
                                profile.UserProfileElement6_Nspecialties = Convert.ToInt32(userProfileElement6_Nspecialties);
                                profile.UserProfileElement7_PercentApps = Convert.ToInt32(userProfileElement7_PercentApps);

                                //Calculate for set of programs. Selects one row at a time from XLS. BulkInsert into DB

                                //THIS ONLY RUNS ONE LINE OF THE METHOD
                                 var backgroundTask = await Task.Run(() =>  CalculateSet(uow, profile, userId, specialtyCode ));

                                //THIS WORKS
                                //CalculateSet(uow, profile, userId, specialtyCode);
                            }

                            i++;

                            Debug.WriteLine("Bulkcreate complete " + i);


                            //only process xxx rows
                            if (i > 1)
                            {
                                break;
                            }
                        }
                    } while (reader.NextResult());
                }
            }

            Debug.WriteLine("Should get here quickly and not wait until task is done");
        }

        private void CalculateSet(UnitOfWork uow, UserProfileData profile, string userId, string specialtyCode)
        {
            //I CAN HIT THIS BREAKPOINT!
            //get specialtyId from code
            var specialtyId = uow.RefMedicalSpecialtyRepository
                 .Find(x => x.Code == specialtyCode).FirstOrDefault().Id;

            //NEVER GET TO THIS BREAKPOINT
            //loop through all programs for speciality
            var programsForSpecialty = uow.RefProgramDetailDataRepository
                .Find(x => x.RefMedicalSpecialtyId == specialtyId);

            //List for bulk insert
           // List<UserProgram> userPrograms = new List<UserProgram>();

            //Write a row for each program
            foreach (RefProgramDetailData rpdd in programsForSpecialty.ToList())
            {
                //Get program info
                var programProfile = LoadData.Load_RefProgramProfileData(rpdd.Code);

                //Calculate results
                var userProgram = _calculator.CalculateAll(programProfile, profile, specialtyId, userId);

                //If the Program can not be found in program detail then skip insert
                if (userProgram == null)
                {
                    Debug.WriteLine("Program NULL");
                }
                else
                {
                    //Write results to UserProgram
                     uow.UserProgramRepository.Create(userProgram);

                    //userPrograms.Add(userProgram);

                    Debug.WriteLine("Program " + programProfile.ProgramCode);
                }
            }

            //bulk insert
           // uow.UserProgramRepository.BulkCreate(userPrograms);
        }
    }
[事实]
公共异步任务计算_Xls()
{
字符串currentDirectory=Directory.GetCurrentDirectory();
字符串filesDirectory=currentDirectory+“\\Files”;
System.Text.Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var builder=new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(“appsettings.json”);
Configuration=builder.Build();
var optionsBuilder=new DbContextOptionsBuilder();
optionsBuilder.UseSqlServer(Configuration.GetConnectionString(“DefaultConnection”));
int i=0;//外部循环
UnitOfWork uow=新的UnitOfWork(新的RetContext(optionsBuilder.Options));
使用(var stream=System.IO.File.Open(filesDirectory+“\\t2UserProfileDataTwoUserPerSpecialty.xlsx”,
FileMode.Open,FileAccess.Read)
{
使用(var reader=ExcelReaderFactory.CreateReader(流))
{
做
{
while(reader.Read())
{
如果(i!=0)
{
var userId=reader.GetString(0);
var specialtyCode=reader.GetString(1);
var userProfileElement1_WorkExp=reader.GetValue(2);
var userProfileElement2_VolExp=reader.GetValue(3);
var userProfileElement3_ResExp=reader.GetValue(4);
var userProfileElement4_Pubs=reader.GetValue(5);
var userProfileElement5_AOA=reader.GetValue(6);
var userProfileElement6_Nspecialties=reader.GetValue(7);
var userProfileElement7_PercentApps=reader.GetValue(8);
//创建配置文件
UserProfileData profile=新的UserProfileData();
profile.UserProfileElement1\u WorkExp=Convert.ToInt32(UserProfileElement1\u WorkExp);
profile.UserProfileElement2\u VolExp=Convert.ToInt32(UserProfileElement2\u VolExp);
profile.UserProfileElement3\u ResExp=Convert.ToInt32(UserProfileElement3\u ResExp);
profile.UserProfileElement4_Pubs=Convert.ToInt32(UserProfileElement4_Pubs);
profile.UserProfileElement5_Aoa=Convert.ToBoolean(UserProfileElement5_Aoa);
profile.UserProfileElement6\u nspecialities=Convert.ToInt32(UserProfileElement6\u nspecialities);
profile.UserProfileElement7_%apps=Convert.ToInt32(UserProfileElement7_%apps);
//计算程序集。从XLS.BulkInsert到DB中一次选择一行
//这只运行方法的一行
var backgroundTask=wait Task.Run(()=>CalculateSet(uow、profile、userId、specialtyCode));
//这很有效
//CalculateSet(uow、配置文件、用户ID、特殊代码);
}
i++;
Debug.WriteLine(“Bulkcreate complete”+i);
//仅处理xxx行
如果(i>1)
{
打破
}
}
}while(reader.NextResult());
}
}
WriteLine(“应该快速到达这里,不要等到任务完成”);
}
私有void CalculateSet(UnitOfWork uow、UserProfileData配置文件、字符串userId、字符串specialtyCode)
{
//我能击中这个断点!
//从代码中获取specialtyId
var specialtyId=uow.RefMedicalSpecialtyRepository
.Find(x=>x.Code==specialtyCode).FirstOrDefault().Id;
//永远不要到达这个断点
//循环浏览所有专业课程
var programsForSpecialty=uow.RefProgramDetailDataRepository
.Find(x=>x.RefMedicalSpecialtyId==specialtyId);
//批量插入列表
//List userPrograms=newlist();
//为每个程序写一行
foreach(programsForSpecialty.ToList()中的RefProgramDetailData rpdd)
{
//获取程序信息
var programProfile=LoadData.Load\U REF PROGRAMPROFILEDATA(rpdd.Code);
//计算结果
var userProgram=\u calculator.CalculateAll(programProfile,profile,specialtyId,userId);
//如果在程序详细信息中找不到该程序,则跳过插入
if(userProgram==null)
{
Debug.WriteLine(“程序空”);
}
其他的
{
//将结果写入用户程序
uow.UserProgramRepository.Create(userProgram);
//添加(userProgram);
Debug.WriteLine(“程序”+programmaprofile.ProgramCo
[Fact]
        public async Task Calculation_Xls()
        {
            string currentDirectory = Directory.GetCurrentDirectory();
            string filesDirectory = currentDirectory + "\\Files";
            System.Text.Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
            Configuration = builder.Build();

            var optionsBuilder = new DbContextOptionsBuilder<RetContext>();
            optionsBuilder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));

            int i = 0; //outer loop

            UnitOfWork uow = new UnitOfWork(new RetContext(optionsBuilder.Options));

            using (var stream = System.IO.File.Open(filesDirectory + "\\t2UserProfileDataTwoUserPerSpecialty.xlsx",
                FileMode.Open, FileAccess.Read))
            {
                using (var reader = ExcelReaderFactory.CreateReader(stream))
                {
                    do
                    {
                        while (reader.Read())
                        {
                            if (i != 0)
                            {
                                var userId = reader.GetString(0);
                                var specialtyCode = reader.GetString(1);
                                var userProfileElement1_WorkExp = reader.GetValue(2);
                                var userProfileElement2_VolExp = reader.GetValue(3);
                                var userProfileElement3_ResExp = reader.GetValue(4);
                                var userProfileElement4_Pubs = reader.GetValue(5);
                                var userProfileElement5_AOA = reader.GetValue(6);
                                var userProfileElement6_Nspecialties = reader.GetValue(7);
                                var userProfileElement7_PercentApps = reader.GetValue(8);

                                //Create profile
                                UserProfileData profile = new UserProfileData();
                                profile.UserProfileElement1_WorkExp = Convert.ToInt32(userProfileElement1_WorkExp);
                                profile.UserProfileElement2_VolExp = Convert.ToInt32(userProfileElement2_VolExp);
                                profile.UserProfileElement3_ResExp = Convert.ToInt32(userProfileElement3_ResExp);
                                profile.UserProfileElement4_Pubs = Convert.ToInt32(userProfileElement4_Pubs);
                                profile.UserProfileElement5_Aoa = Convert.ToBoolean(userProfileElement5_AOA);
                                profile.UserProfileElement6_Nspecialties = Convert.ToInt32(userProfileElement6_Nspecialties);
                                profile.UserProfileElement7_PercentApps = Convert.ToInt32(userProfileElement7_PercentApps);

                                //Calculate for set of programs. Selects one row at a time from XLS. BulkInsert into DB

                                //THIS ONLY RUNS ONE LINE OF THE METHOD
                                 var backgroundTask = await Task.Run(() =>  CalculateSet(uow, profile, userId, specialtyCode ));

                                //THIS WORKS
                                //CalculateSet(uow, profile, userId, specialtyCode);
                            }

                            i++;

                            Debug.WriteLine("Bulkcreate complete " + i);


                            //only process xxx rows
                            if (i > 1)
                            {
                                break;
                            }
                        }
                    } while (reader.NextResult());
                }
            }

            Debug.WriteLine("Should get here quickly and not wait until task is done");
        }

        private void CalculateSet(UnitOfWork uow, UserProfileData profile, string userId, string specialtyCode)
        {
            //I CAN HIT THIS BREAKPOINT!
            //get specialtyId from code
            var specialtyId = uow.RefMedicalSpecialtyRepository
                 .Find(x => x.Code == specialtyCode).FirstOrDefault().Id;

            //NEVER GET TO THIS BREAKPOINT
            //loop through all programs for speciality
            var programsForSpecialty = uow.RefProgramDetailDataRepository
                .Find(x => x.RefMedicalSpecialtyId == specialtyId);

            //List for bulk insert
           // List<UserProgram> userPrograms = new List<UserProgram>();

            //Write a row for each program
            foreach (RefProgramDetailData rpdd in programsForSpecialty.ToList())
            {
                //Get program info
                var programProfile = LoadData.Load_RefProgramProfileData(rpdd.Code);

                //Calculate results
                var userProgram = _calculator.CalculateAll(programProfile, profile, specialtyId, userId);

                //If the Program can not be found in program detail then skip insert
                if (userProgram == null)
                {
                    Debug.WriteLine("Program NULL");
                }
                else
                {
                    //Write results to UserProgram
                     uow.UserProgramRepository.Create(userProgram);

                    //userPrograms.Add(userProgram);

                    Debug.WriteLine("Program " + programProfile.ProgramCode);
                }
            }

            //bulk insert
           // uow.UserProgramRepository.BulkCreate(userPrograms);
        }
    }