我尝试使用Parallel.ForEach
从主线程执行我的任务:
private List<MyData> MyCollection;
private static CancellationTokenSource _tokenSource;
private void Start()
{
ThreadStart threadStart = delegate
{
var token = _tokenSource.Token;
Task.Factory.StartNew(() =>
{
try
{
Parallel.ForEach(MyCollection,
new ParallelOptions
{
MaxDegreeOfParallelism = (int)nudConcurrentFiles.Value //limit number of parallel threads
},
file =>
{
if (token.IsCancellationRequested)
return;
//do work...
});
}
catch (Exception e)
{ }
}, _tokenSource.Token,
TaskCreationOptions.None,
TaskScheduler.Default).ContinueWith(
t =>
{
}
, TaskScheduler.FromCurrentSynchronizationContext() //to ContinueWith (update UI) from UI thread
);
};
Thread thread = new Thread(threadStart);
thread.IsBackground = true;
thread.Start();
}
在出现错误后:
调用线程无法访问此对象,因为不同的线程拥有它。
我也尝试使用不同的Thread
和Parallel.ForEach
,但仍然出现相同的错误。
TaskScheduler.FromCurrentSynchronizationContext
已经在非 UI 线程上运行。同样的方式,nudConcurrentFiles
也是从这个非 UI 线程中访问的。 - LuaanTaskScheduler.FromCurrentSynchronizationContext
。只需摆脱整个外层线程,因为它毫无意义。 - Luaan