如何取消MVC.NET中的任务

时间:2015-03-25 08:31:25

标签: asp.net-mvc-4 task-parallel-library

我有一个页面有两个命令“RUN”“取消”。 我的问题:如何点击“取消”从任务进入“运行”取消?

TryTask:启动任务 取消:退出任务TryTask

CancellationTokenSource source = new CancellationTokenSource

        private async Task TryTask()
        {
            Task<int> task = Task.Run(() => slowFunc(1, 2), source.Token);

            // (A canceled task will raise an exception when awaited).

            source.Cancel();
            await task;
        }

        string someString = string.Empty;

        public int slowFunc(int a, int b)
        {
            for (int i = 0; i < 200000000; i++)
            {
                someString += "a";
                    source.Cancel();                    
                source.Token.ThrowIfCancellationRequested();
            }

            return a + b;
        }


        public async Task<ActionResult> Cancel()
        {
            "how cancel slow function"
        }

0 个答案:

没有答案