public void Read(string file)
{
_read ?? = new Thread(() => MethodA(file));
_read.Start();
}
private void CancelReading()
{
if (_read != null)
{
if (!_read.Join(100))
_read.Abort();
_read = null;
}
}
private void MethodA(string file)
{
try
{
Thread.Sleep(300);
MethodB(file);
}
catch (Exception ex)
{
Trace.TraceError(ex.Message);
ErrorMethod();
}
}
private void ErrorMethod()
{
CancelReading();
}
Here in this code, the line _read.Abort()
shows a warning about “Thread.Abort is obsolete”. Is there any workaround or any alternatives for this?
I’ve tried one using CancellationToken, but couldn’t resolve the issue. Here is the implementation using CancellationToken –
public void Read(string file)
{
CancelReading();
_cancellationTokenSource = new CancellationTokenSource();
_readTask = Task.Run(() => MethodA(file, _cancellationTokenSource.Token));
}
private void CancelReading()
{
if (_cancellationTokenSource != null)
{
_cancellationTokenSource.Cancel();
_cancellationTokenSource.Dispose();
_cancellationTokenSource = null;
}
}
private void MethodA(string file, CancellationToken cancellationToken)
{
try
{
cancellationToken.ThrowIfCancellationRequested();
Thread.Sleep(300);
cancellationToken.ThrowIfCancellationRequested();
MethodB(file);
}
catch (Exception ex)
{
Trace.TraceError(ex.Message);
ErrorMethod();
}
}
private void ErrorMethod()
{
CancelReading();
}
Could anyone please help me to resolve this issue whether using CancellationToken or any other ways?
New contributor
fahmid07 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.