我已經閱讀了很多關於如何返回任務的值,但我似乎無法讓它在我的代碼上工作,仍然產生System.Threading.ThreadAbortException
。C#任務返回輸出
嘗試使用Task.WaitAll
即使這可能會阻止用戶界面,但無濟於事。
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;
}
}
嘗試使用ContinueWhenAll
但仍然相同。
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;
}
}
的DoTask
僅僅是檢查和查詢數據庫的方法。
private DataTable DoTask(SomeVariable someVariable)
{
DataTable matchedData = new DataTable();
// long database process/query
// populate and return matchedData
return matchedData;
}
編輯:參考如何/爲什麼它被使用。
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");
});
你爲什麼想在這種情況下使用任務? –
請參閱上面的更新代碼。 – RaMa
請將該代碼添加到原始文章中,以便格式正確,並且每個人都可以將其視爲問題的一部分。 –