可能重复:
如何创建运行STA线程的任务(TPL)?
我正在使用以下代码:
var task = Task.Factory.StartNew<List<NewTwitterStatus>>(
() => GetTweets(securityKeys),
TaskCreationOptions.LongRunning);
Dispatcher.BeginInvoke(DispatcherPriority.Background,
new Action(() =>
{
var result = task.Result; // ERROR!!! The calling thread cannot access this object because a different thread owns it.
RecentTweetList.ItemsSource = result;
Visibility = result.Any() ? Visibility.Visible : Visibility.Hidden;
}));
Run Code Online (Sandbox Code Playgroud)
我收到了错误:
var result = task.Result; // ERROR!!! The calling thread cannot access this object because a different thread owns it.
Run Code Online (Sandbox Code Playgroud)
我该怎么做才能解决这个问题?
我有这个简单的代码:
var g= Task.Factory.StartNew<int> (() => 8)
.ContinueWith (ant =>{throw null;})
.ContinueWith (a =>{ Console.WriteLine("OK");},TaskContinuationOptions.NotOnFaulted);
try{
Console.WriteLine("1");
g.Wait();
Console.WriteLine("2");
}
catch (AggregateException ex)
{Console.WriteLine("catch"); }
Run Code Online (Sandbox Code Playgroud)
输出 :
1
catch
System.AggregateException: A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread.
Run Code Online (Sandbox Code Playgroud)
msdn:
TaskContinuationOptions.NotOnFaulted
指定如果延续任务的前端抛出未处理的异常,则不应该对其进行调度.此选项对多任务延续无效.
好 .

并且没关系 - 不显示此行导致prev行DID抛出异常.
问题:
我是否AggregateException因为没有检查过Exception房产而得到例外?
我是否必须始终检查先前是否会抛出异常(在每一行?)?(我不能检查每一行!它没有任何意义,非常烦人)
是不是该try …
我想实现优先顺序ActionBlock<T>.因此我可以TInput通过使用a 来有条件地优先考虑某些项目Predicate<T>.
我阅读了 Parallel Extensions Extras示例和实现自定义TPL数据流块的指南.
但仍然没有弄清楚如何实现这种情况.
---------------------------- EDIT --------------------- ------
有一些任务,其中5个可以同时运行.当用户按下按钮时,一些(取决于谓词函数)任务应该以最高优先级运行.
实际上我写了这段代码
TaskScheduler taskSchedulerHighPriority;
ActionBlock<CustomObject> actionBlockLow;
ActionBlock<CustomObject> actionBlockHigh;
...
queuedTaskScheduler = new QueuedTaskScheduler(TaskScheduler.Default, 5);
taskSchedulerHigh = queuedTaskScheduler.ActivateNewQueue(0);
taskSchedulerLow = queuedTaskScheduler.ActivateNewQueue(1);
...
actionBlockHigh = new ActionBlock<CustomObject>(new Action<CustomObject>(method), new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 5, SingleProducerConstrained = false, TaskScheduler = taskSchedulerHigh });
actionBlockLow = new ActionBlock<CustomObject>(new Action<CustomObject>(method), new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 5, MaxMessagesPerTask = 1, TaskScheduler = taskSchedulerLow });
...
if (predicate(customObject)) …Run Code Online (Sandbox Code Playgroud) c# multithreading task-parallel-library .net-4.5 tpl-dataflow
在我的ASP.NET MVC4应用程序中,我有一个控制器操作,我可以在其中访问多个外部网站并收集我在页面上以聚合方式显示的信息.显然,我想并行执行此操作,因此我编写了类似于此的代码:
var client1 = new HttpClient().GetAsync("http://google.com");
var client2 = new HttpClient().GetAsync("http://stackoverflow.com");
var client3 = new HttpClient().GetAsync("http://twitter.com");
var result1 = client1.Result;
var result2 = client2.Result;
var result3 = client3.Result;
Run Code Online (Sandbox Code Playgroud)
如何找出每个请求完成的时间,以便我可以在我的页面上显示该信息?
我正在尝试实现Parallel.ForEach模式并跟踪进度,但我遗漏了一些有关锁定的内容.以下示例计数为1000时threadCount = 1,但不是threadCount> 1. 当正确的方法是什么时候?
class Program
{
static void Main()
{
var progress = new Progress();
var ids = Enumerable.Range(1, 10000);
var threadCount = 2;
Parallel.ForEach(ids, new ParallelOptions { MaxDegreeOfParallelism = threadCount }, id => { progress.CurrentCount++; });
Console.WriteLine("Threads: {0}, Count: {1}", threadCount, progress.CurrentCount);
Console.ReadKey();
}
}
internal class Progress
{
private Object _lock = new Object();
private int _currentCount;
public int CurrentCount
{
get
{
lock (_lock)
{
return _currentCount;
}
} …Run Code Online (Sandbox Code Playgroud) 我有一个像这样的异步任务:
public async Task DoWork()
{
}
Run Code Online (Sandbox Code Playgroud)
我现在有一个:
List<Task> tmp = new List<Task>();
Run Code Online (Sandbox Code Playgroud)
在哪里我添加任务.
我开始这样的任务:
foreach (Task t in tmp)
{
await t;
}
Run Code Online (Sandbox Code Playgroud)
现在我的问题:
什么是启动任务的最佳方式,同时只运行其中3个(直到其他人等待)?
我想我需要像队列/等待名单一样的东西?
在队列启动后还应该可以添加更多任务.
我使用的是.NET 4.5.
谢谢你的任何建议
这是这个问题的延续: 多任务延续
我在答案中更改了我的代码,但是现在我在TaskCancelledExceptions尝试运行任务时收到了.
public virtual async Task RunAsync(TaskWithProgress task)
{
Show();
TaskIsRunning();
await SetCompletedHandler(TaskComplete());
await SetCancelledHandler(TaskCancelled())
await SetFaultedHandler(TaskFaulted());
await task;
Close();
}
Run Code Online (Sandbox Code Playgroud)
但是以下代码没有.我有点卡住原因.
public virtual Task RunAsync(TaskWithProgress task)
{
Show();
TaskIsRunning();
SetCompletedHandler(TaskComplete());
SetCancelledHandler(TaskCancelled())
SetFaultedHandler(TaskFaulted());
return task;
}
Run Code Online (Sandbox Code Playgroud)
调用代码基本上涉及以下内容:
await progressDialog.RunAsync(task);
Run Code Online (Sandbox Code Playgroud)
编辑:
我没有取消cancellationtoken任何地方,所以我不明白为什么这会抛出异常.
三个SetXXXHandler()方法基本上执行以下具有不同延续状态的代码:
task.ContinueWith(_ => action(), CancellationToken.None, TaskContinuationOptions.OnlyOnCanceled, this.Scheduler);
Run Code Online (Sandbox Code Playgroud)
堆栈跟踪在这里:
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at FugroDXExt.frmBaseProgressAsync.<RunAsync>d__7.MoveNext() in d:\C#\FugroDXExt\trunk\frmBaseProgressAsync.cs:line 92
--- End of stack trace from previous location where exception was thrown --- …Run Code Online (Sandbox Code Playgroud) 我正在创建一段代码,从我们拥有的遗留系统中获取网页.为了避免过多的查询,我正在缓存获取的URL.我正在使用Monitor.Enter,Monitor.Exit并仔细检查以避免该请求被发出两次,但在释放锁定时Monitor.Exit,我得到此异常:
System.Threading.SynchronizationLockException was caught
HResult=-2146233064
Message=Object synchronization method was called from an unsynchronized block of code.
Source=MyApp
StackTrace:
at MyApp.Data.ExProvider.<OpenFeature>d__0.MoveNext() in c:\Users\me\Documents\Visual Studio 2013\Projects\MyApp\MyApp\Data\ExProvider.cs:line 56
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at MyApp.Data.ExProvider.<GetSupportFor>d__15.MoveNext() in c:\Users\me\Documents\Visual Studio 2013\Projects\MyApp\MyApp\Data\ExProvider.cs:line 71
InnerException:
Run Code Online (Sandbox Code Playgroud)
线56是Monitor.Exit.这是执行操作的代码:
private async Task<Stream> OpenReport(String report)
{
var file = _directory.GetFiles(report+ ".html");
if (file != null && file.Any()) …Run Code Online (Sandbox Code Playgroud) c# multithreading synchronization task-parallel-library async-await
我手动构建一个任务:
var task = new Task(() =>
Debug.WriteLine("Task"));
Run Code Online (Sandbox Code Playgroud)
然后手动启动它:
task.Start(TaskScheduler.FromCurrentSynchronizationContext());
Run Code Online (Sandbox Code Playgroud)
我希望它能通过预定SynchronizationContext.Post.
但如果以这种方式启动它:
task.RunSynchronously(TaskScheduler.FromCurrentSynchronizationContext());
Run Code Online (Sandbox Code Playgroud)
是通过SynchronizationContext.Send调用任务的lambda 来执行还是直接执行?
我有以下代码,我想测试:
private Task _keepAliveTask; // get's assigned by object initializer
public async Task EndSession()
{
_cancellationTokenSource.Cancel(); // cancels the _keepAliveTask
await _logOutCommand.LogOutIfPossible();
await _keepAliveTask;
}
Run Code Online (Sandbox Code Playgroud)
重要的是,EndSession只有`_keepAliveTask'结束后,Task才会结束.但是,我很难找到一种方法来可靠地测试它.
问题:我如何对EndSession方法进行单元测试并验证等待Task返回的方法.EndSession_keepAliveTask
出于演示目的,单元测试可能如下所示:
public async Task EndSession_MustWaitForKeepAliveTaskToEnd()
{
var keepAliveTask = new Mock<Task>();
// for simplicity sake i slightly differ from the other examples
// by passing the task as method parameter
await EndSession(keepAliveTask);
keepAliveTask.VerifyAwaited(); // this is what i want to achieve
}
Run Code Online (Sandbox Code Playgroud)
进一步的标准: - …
c# ×10
.net ×5
async-await ×4
asynchronous ×2
.net-4.0 ×1
.net-4.5 ×1
locking ×1
task ×1
throttling ×1
tpl-dataflow ×1
unit-testing ×1
wpf ×1