0
Reply

How to end Running task immediadtely

Ask a question
pintu patil

pintu patil

12y
1.6k
1
namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public int q;
        SoundPlayer player = new SoundPlayer();
      
        public void Test(int flag)
        {

            CancellationTokenSource tokenSource = new CancellationTokenSource();
            CancellationToken token = tokenSource.Token;
            var u=Task.Factory.StartNew(()=>
            {
            
                  if (token.IsCancellationRequested)
                  {
                     player.Stop();
                     throw new OperationCanceledException(token);
                  }
                  else
                  {
              
                    player.SoundLocation=@"D:\AudioOut\final.wav";
                    {
                      for (int i = 0; i < 2; i++)
                     {
                         player.PlaySync();
                     }
                   }
                 }
                }, token);

            if (flag == 1)
            {

                
                u.Start();
                
               
            }
            else if(flag==0)
            {
                    
                    token.ThrowIfCancellationRequested();
                    tokenSource.Cancel();
                    u.Dispose();
            }
           
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
           
           

            Test(1);
        }

        private void Show_Click(object sender, EventArgs e)
        {
            MessageBox.Show(" askdsa;kd;aslkdsa;ldk;asldk");
        }

        private void Stop_Click(object sender, EventArgs e)
        {
            Test(0);
        
            
        }
    }
}




i want to stop PlaySync immediately.But not working.using cancel method task will assign id other than from running task id.and cancel differnet task not a running task i.e. playsync


plz provide solution