为了账号安全,请及时绑定邮箱和手机立即绑定

如何在主线程中调用一个方法并终止另一个线程?

如何在主线程中调用一个方法并终止另一个线程?

C#
泛舟湖上清波郎朗 2022-12-31 11:20:26
所以我启动了一个对列表进行排序的线程,完成后它应该在我的控制器中调用“completedSorting()”方法。现在我担心仅仅调用该方法会导致该方法在另一个线程中执行。我相当擅长 C#,但线程对我来说是一个新概念。我只想返回线程,但是当我一次运行多个排序时,这只会导致混淆我 reccon,因此我希望他们调用“completedSorting”方法控制器:        public void StartAlgorithm(Algorithm algorithm)        {            // check listOfArrays            if (listManager.arrayList.Count == 0)            {                       int[] newArray = CreateArray(algorithm.currentListLength);                listManager.arrayList.Add(newArray);                listManager.currentBiggestList = newArray.Length;                Thread thread = new Thread(() => algorithm.SolveAlgorithm(newArray, algorithm));                thread.Start();冒泡排序:        public override void SolveAlgorithm(int[] arr, Algorithm algorithm)        {            int temp = 0;            for (int write = 0; write < arr.Length; write++)            {                for (int sort = 0; sort < arr.Length - 1; sort++)                {                    if (arr[sort] > arr[sort + 1])                    {                        temp = arr[sort + 1];                        arr[sort + 1] = arr[sort];                        arr[sort] = temp;                    }                }            }            CompletedAlgorithmLog newlog = new CompletedAlgorithmLog(filteredArray, algorithm);            this.controller.OnCompletedArray(newlog);最后一行是我需要更改一些代码的地方,我认为我必须在执行 mainthread=>completedSorting 之类的操作后返回,但我不知道具体如何操作。
查看完整描述

1 回答

?
慕容森

TA贡献1853条经验 获得超18个赞

使用 Task Parallel 库并使用 Task Continuation


System.Threading.Tasks.Task

.Run(() => 

{

    StartAlgorithm(algorithm);

})

.ContinueWith(()=>{


  CompletedAlgorithmLog newlog = new CompletedAlgorithmLog(filteredArray, algorithm);

            this.controller.OnCompletedArray(newlog);


});

它将在与线程池不同的线程上运行算法,一旦完成,将在 continueWith 中执行代码。


查看完整回答
反对 回复 2022-12-31
  • 1 回答
  • 0 关注
  • 56 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信