2

Hello I’m new to multithreading and tasks in C# .net from only help I have succeeded to start a new task taht can keep running inbackground using:

//if(tsk =NotRunning){
tsk = Task.Factory.StartNew(TheMethod);

It is working fine by now but now when its started am unable to stop it now, I have been searching over msdn and found out few method that seems to be doing the job like Dispose buy they are not doing it, so I want to know two things:

  • How can I check whether this task is already running? (it’s an MVC project and the task is initiate with the controller call …/Task/Start so I don’t want to keep starting another instance of the task everytime this URL is accessed I want only one instance of it throughout the application running in the background)

  • Second how do I stop it than, I tried the following but didn’t work:

    public void TaskClose()
    {
        tsk.Dispose();
        var st = tsk.Status.ToString();
    }
    

I know there may be few answers regarding it available on internet but they mostly using Lambda expression and I am not very rehearsed with them so kindly provide answer in other way, I will even appreciate of you can point the right method or property name that I can use to accomplish my result.

Thank you.

4

1 に答える 1

4

TPLタスクを停止することはできません。これを処理する適切な方法は、キャンセルトークンを実装することです。

于 2012-11-20T13:36:02.397 に答える