How do I abort/cancel TPL Tasks?

前端 未结 12 2281
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 11:42

In a thread, I create some System.Threading.Task and start each task.

When I do a .Abort() to kill the thread, the tasks are not aborted.

12条回答
  •  醉梦人生
    2020-11-22 11:56

    I tried CancellationTokenSource but i can't do this. And i did do this with my own way. And it works.

    namespace Blokick.Provider
    {
        public class SignalRConnectProvider
        {
            public SignalRConnectProvider()
            {
            }
    
            public bool IsStopRequested { get; set; } = false; //1-)This is important and default `false`.
    
            public async Task ConnectTab()
            {
                string messageText = "";
                for (int count = 1; count < 20; count++)
                {
                    if (count == 1)
                    {
                    //Do stuff.
                    }
    
                    try
                    {
                    //Do stuff.
                    }
                    catch (Exception ex)
                    {
                    //Do stuff.
                    }
                    if (IsStopRequested) //3-)This is important. The control of the task stopping request. Must be true and in inside.
                    {
                        return messageText = "Task stopped."; //4-) And so return and exit the code and task.
                    }
                    if (Connected)
                    {
                    //Do stuff.
                    }
                    if (count == 19)
                    {
                    //Do stuff.
                    }
                }
                return messageText;
            }
        }
    }
    

    And another class of the calling the method:

    namespace Blokick.Views
    {
        [XamlCompilation(XamlCompilationOptions.Compile)]
        public partial class MessagePerson : ContentPage
        {
            SignalRConnectProvider signalR = new SignalRConnectProvider();
    
            public MessagePerson()
            {
                InitializeComponent();
    
                signalR.IsStopRequested = true; // 2-) And this. Make true if running the task and go inside if statement of the IsStopRequested property.
    
                if (signalR.ChatHubProxy != null)
                {
                     signalR.Disconnect();
                }
    
                LoadSignalRMessage();
            }
        }
    }
    

提交回复
热议问题