gpt4 book ai didi

c# - 如何从主 UI 线程使用 Parallel.ForEach

转载 作者:太空狗 更新时间:2023-10-30 01:34:07 24 4
gpt4 key购买 nike

我尝试使用 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();
}

出现错误后:

The calling thread cannot access this object because a different thread owns it.

我也尝试将此 Parallel.ForEach 与不同的 Thread 一起使用,但出现了同样的错误。

最佳答案

Parallel.ForEach 的主体始终在线程池线程上执行。您无法在那里访问 UI 控件。在 UI 线程上提取您需要的所有值。无论如何,这是更简洁的代码:

var maxDOP = (int) nudConcurrentFiles.Value; //on UI thread

P.ForEach(..., () => { use maxDop here }); //in Task

关于c# - 如何从主 UI 线程使用 Parallel.ForEach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31904376/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com