I've read a lot on how to return value for a task but I can't seem to get it to work on my code and still produces the System.Threading.ThreadAbortException.
Tried using Task.WaitAll even though this might block the UI but to no avail.
public DataTable GetResult(SomeVariable someVariable) {
// this do not work
//var task = Task<DataTable>.Factory.StartNew(() =>
var task = Task.Factory.StartNew<DataTable>(() =>
{
DataTable matchedData = new DataTable();
matchedData = DoTask(someVariable);
return matchedData;
}, TaskCreationOptions.LongRunning);
try
{
var allTasks = new Task[] { task };
Task.WaitAll(allTasks);
return task.Result as DataTable;
}
catch (ArgumentException)
{
throw;
}
catch (Exception)
{
// Always get the exception here: "A first chance exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll"
throw;
}
}
Tried using ContinueWhenAll but still the same.
public DataTable GetResultV2(SomeVariable someVariable)
{
queue = new Queue<Task>();
DataTable matchedData = new DataTable();
var task = Task.Factory.StartNew(() =>
{
matchedData = DoTask(someVariable);
return matchedData;
}, TaskCreationOptions.LongRunning);
queue.Enqueue(task);
try
{
var done = Task.Factory.ContinueWhenAll(queue.ToArray(), completed =>
{
return matchedData;
});
return done.Result as DataTable;
}
catch (ArgumentException)
{
throw;
}
catch (Exception)
{
// Always get the exception here: "A first chance exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll"
throw;
}
}
The DoTask is just a method that checks and query databases.
private DataTable DoTask(SomeVariable someVariable)
{
DataTable matchedData = new DataTable();
// long database process/query
// populate and return matchedData
return matchedData;
}
edit: For reference on how/why it's being used.
foreach (DataRow row in data.Rows)
{
string columnName = Convert.ToString(row["columnName"]);
string ProjectName = Convert.ToString(row["ProjectName"]);
string dbase_group = Convert.ToString(row["dbase_group"]);
string dbase_data = Convert.ToString(row["dbase_data"]);
var task = Task.Factory.StartNew(() =>
{
SomeVariable someVariable = new SomeVariable();
someVariable.DbName = dbase_group;
someVariable.columnName = columnName;
someVariable.ProjectName = ProjectName;
someVariable.TblName = dbase_data;
using (SearchProject search = new SearchProject())
{
DataTable result = new DataTable();
result = search.GetResult(SomeVariable);
}
});
queue.Enqueue(task);
}
Task.Factory.ContinueWhenAll(queue.ToArray(), ant =>
{
Console.WriteLine("Done with all tasks");
});
Tasks, there's no opportunity for aThread.Abortfrom the inside. Try searching your whole code base forThread.Abort. Also, you do realize you're never returning theresult, right?