虽然我将在这里谈论的代码我在F#中编写,但它基于.NET 4框架,而不是特别依赖于F#的任何特殊性(至少看起来如此!).
我的磁盘上有一些数据,我应该从网络更新,将最新版本保存到磁盘:
type MyData =
{ field1 : int;
field2 : float }
type MyDataGroup =
{ Data : MyData[];
Id : int }
// load : int -> MyDataGroup
let load dataId =
let data = ... // reads from disk
{ Data = data;
Id = dataId }
// update : MyDataGroup -> MyDataGroup
let update dg =
let newData = ... // reads from the network and process
// newData : MyData[]
{ dg with …Run Code Online (Sandbox Code Playgroud) .net parallel-processing f# parallel-extensions task-parallel-library
这可能是我错过的简单事情.
让我说我做(在loveley VB中):
Dim t1 As New Task(Sub() Debug.WriteLine("t1"))
Dim t2 As Task = t1.ContinueWith(Sub() Debug.WriteLine("t2"))
Dim t3 As Task = t1.ContinueWith(Sub() Debug.WriteLine("t3"))
t1.Start()
Run Code Online (Sandbox Code Playgroud)
注意t1.ContinueWith使用两次.这些任务的首选执行顺序是什么?对我来说,无论是随机还是错误.
我想这样做的原因......
TaskScheduler.FromCurrentSynchronizationContext()UI线程上""分类"UI由于步骤4是可选的,因此这变得更加复杂.
在所有这些中,我的任务向后弯曲以设置成员属性,因此UI和任务可以很好地发挥作用.也许我应该完全放弃任务结果,只是坚持Synclocking我的成员变量.它们都只是一次性分配.
谢谢,汤姆
据我所知,我有一些误导性的信息.我需要在后台运行一个单独的线程.
目前我这样做:
var task = Task.Factory.StartNew
(CheckFiles
, cancelCheckFile.Token
, TaskCreationOptions.LongRunning
, TaskScheduler.Default);//Check for files on another thread
private void CheckFiles()
{
while (!cancelCheckFile.Token.IsCancellationRequested)
{
//do stuff
}
}
Run Code Online (Sandbox Code Playgroud)
这总是为我创建一个新线程.但经过多次讨论后,即使将其标记为LongRunning也无法保证将创建新的线程.
在过去我做过这样的事情:
thQueueChecker = new Thread(new ThreadStart(CheckQueue));
thQueueChecker.IsBackground = true;
thQueueChecker.Name = "CheckQueues" + DateTime.Now.Ticks.ToString();
thQueueChecker.Start();
private void CheckQueue()
{
while (!ProgramEnding)
{
//do stuff
}
}
Run Code Online (Sandbox Code Playgroud)
你会建议我回到这种方法来保证使用新线程吗?
我特别想要在一个或另一个中编写一些信号处理算法,或者两者兼而有之.
表现并不是一个大问题,表达意图的清晰度更为重要.
我想要实现以下'Blocks'并组成它们:
我认为Rx可以被认为是'Linq-to-streams',而TPL是对并发的抽象.我还得到Rx在内部使用TPL来管理其异步位,并且TPL数据流为TPL增加了可组合性.
所以两者都是异步的,都是可组合的,都是相当高的水平(Rx更多).通常和上面的信号处理项目应该在哪里使用?
signal-processing dataflow task-parallel-library system.reactive tpl-dataflow
所以我有一些代码
Task.Factory.StartNew(() => this.listener.Start()).ContinueWith(
(task) =>
{
if (task.IsCompleted)
{
this.status = WorkerStatus.Started;
this.RaiseStatusChanged();
this.LogInformationMessage("Worker Started.");
}
});
Run Code Online (Sandbox Code Playgroud)
当我测试时,我正在模拟所有依赖对象(namley this.listener.Start()).问题是测试在ContinueWith被调用之前完成执行.当我调试时,由于我单步执行代码的额外延迟,它被称为罚款.
那么我怎么能 - 从不同程序集中的测试代码 - 确保代码在我的测试遇到其断言之前运行?
我可以使用Thread.Sleep ......但这似乎是一种真正的hacky方式.
我想我正在寻找Thread.Join的Task版本.
我在使用时遇到了一个问题,Task.Factory.StartNew并试图捕获exception被抛出的问题.在我的应用程序中,我有一个长期运行的任务,我想封装在一个Task.Factory.StartNew(.., TaskCreationOptions.LongRunning);
但是,当我使用时,没有捕获异常Task.Factory.StartNew.然而,当我使用时Task.Run,它正如我所期望的那样工作,我认为它只是一个包装器Task.Factory.StartNew(根据例如这篇MSDN文章).
这里提供了一个工作示例,不同之处在于在使用时将异常写入控制台Task.Run,但在使用时不会Factory.StartNew.
我的问题是:
如果我有一个LongRunning可以抛出异常的任务,我应该如何在调用代码中处理它们?
private static void Main(string[] args)
{
Task<bool> t = RunLongTask();
t.Wait();
Console.WriteLine(t.Result);
Console.ReadKey();
}
private async static Task<bool> RunLongTask()
{
try
{
await RunTaskAsync();
}
catch (Exception e)
{
Console.WriteLine(e);
return false;
}
Console.WriteLine("success");
return true;
}
private static Task RunTaskAsync()
{
//return Task.Run(async () =>
// {
// throw new Exception("my exception");
// }); …Run Code Online (Sandbox Code Playgroud) 在连续链中传播异常的正确方法是什么?
t.ContinueWith(t2 =>
{
if(t2.Exception != null)
throw t2.Exception;
/* Other async code. */
})
.ContinueWith(/*...*/);
t.ContinueWith(t2 =>
{
if(t2.IsFaulted)
throw t2.Exception;
/* Other async code. */
})
.ContinueWith(/*...*/);
t.ContinueWith(t2 =>
{
if(t2.Exception != null)
return t2;
/* Other async code. */
})
.ContinueWith(/*...*/);
t.ContinueWith(t2 =>
{
if(t2.IsFaulted)
return t2;
/* Other async code. */
})
.ContinueWith(/*...*/);
t.ContinueWith(t2 =>
{
t2.Wait();
/* Other async code. */
})
.ContinueWith(/*...*/);
t.ContinueWith(t2 =>
{
/* Other async code. */
}, TaskContinuationOptions.NotOnFaulted) // Don't …Run Code Online (Sandbox Code Playgroud) 例
private void Start(object sender, RoutedEventArgs e)
{
int progress = 0;
for (;;)
{
System.Threading.Thread.Sleep(1);
progress++;
Logger.Info(progress);
}
}
Run Code Online (Sandbox Code Playgroud)
如果我想要Start(),建议的方法是什么(TAP或TPL或BackgroundWorker或Dispatcher或其他)
我有以下代码行用于从NetworkStream异步读取:
int bytesRead = await Task<int>.Factory.FromAsync(this.stream.BeginRead, this.stream.EndRead, buffer, 0, buffer.Length, null);
Run Code Online (Sandbox Code Playgroud)
我想支持取消.我看到我可以使用CancellationTokenSource取消任务,但是我没有看到任何方法可以将它传递给TaskFactory.FromAsync().
是否可以使FromAsync()构造的任务支持取消?
编辑:我想取消已经运行的任务.
假设我在一个类中有一个成员变量(具有原子读/写数据类型):
bool m_Done = false;
Run Code Online (Sandbox Code Playgroud)
后来我创建了一个将其设置为true的任务:
Task.Run(() => m_Done = true);
Run Code Online (Sandbox Code Playgroud)
我不在乎什么时候m_Done将被设置为true.我的问题是,我是否有C#语言规范和任务并行库的保证,如果我从不同的线程访问它,最终m_Done将成立?
例:
if(m_Done) { // Do something }
Run Code Online (Sandbox Code Playgroud)
我知道使用锁会引入必要的内存障碍,m_Done将在以后显示为true.此外,我可以在设置变量时使用Volatile.Write,在读取时使用Volatile.Read.我看到很多代码以这种方式编写(没有锁或易失性),我不确定它是否正确.
请注意,我的问题不是针对C#或.Net的特定实现,而是针对规范.如果在x86,x64,Itanium或ARM上运行,我需要知道当前代码的行为是否相似.
c# multithreading volatile memory-model task-parallel-library
c# ×7
.net ×3
exception ×2
task ×2
.net-4.0 ×1
continuation ×1
dataflow ×1
f# ×1
memory-model ×1
moq ×1
nunit ×1
tap ×1
taskfactory ×1
tpl-dataflow ×1
unit-testing ×1
volatile ×1
wpf ×1