Reputation: 1205
I am working calling app which automatically calls a number. I am using main thread to query call status(busy,dialing,active, calling, deactivated etc). Whenever call is picked recorded audio will be played using other thread 2. When call status is deactivated main thread will stop audio by stopping thread 2. On next call again when call is picked recorded audio will played using thread 2.
Thread autoReminder = new Thread(new ThreadStart(threadAutoCalling));
//// Main thread on call attend calls
autoReminder.Start();
// On call end, i tried
autoReminder.Abort();
private void threadAutoCalling()
{
try
{
// PlayAudio(@"C:\Users\CheatnPc\Desktop\TextToSpeechAudio\psf1.wav");
PlayAudio(@"C:\Users\CheatnPc\Desktop\TextToSpeechAudio\psf3.wav");
PlayAudio(@"C:\Users\CheatnPc\Desktop\TextToSpeechAudio\sales.wav");
}
catch (Exception ex)
{
throw ex;
}
}
public void PlayAudio(string path)
{
(new Microsoft.VisualBasic.Devices.Audio()).Play(path, Microsoft.VisualBasic.AudioPlayMode.WaitToComplete);
}
after thread abort it can not be started again. How can i do this or is there any alternate solution for this.
Upvotes: 0
Views: 66
Reputation: 38114
As I understood correctly you want to abort your play of music. For this reason it is more applicable Task
class. You can cancel your Task
by calling Cancel()
method of class CancellationTokenSource
.
Example of console application:
CancellationTokenSource cancellationTokenSource =
new CancellationTokenSource();
CancellationToken token = cancellationTokenSource.Token;
Task task = Task.Run(() =>
{
while (!token.IsCancellationRequested)
{
ThreadAutoCalling();
}
token.ThrowIfCancellationRequested();
}, token);
try
{
Console.WriteLine("Press any key to abort the task");
Console.ReadLine();
cancellationTokenSource.Cancel();
task.Wait();
}
catch (AggregateException e)
{
Console.WriteLine(e.InnerExceptions[0].Message);
}
Upvotes: 0
Reputation: 63732
Thread's cannot be restarted - when they're done, they're done.
The usual solution would be to simply start a new thread, but when you're doing as little as you are, using a threadpool thread might be a better idea:
Task.Run(threadAutoCalling);
Or even better, if there's an asynchronous way of invoking those PlaySound
and Speak
, use that - usually, you wouldn't need real CPU work to handle operations like that.
Upvotes: 1