我正在尝试学习如何使用 TPL。我已经对这个主题进行了大量阅读,但我不明白为什么以下代码示例会中断,而之后的代码示例会中断?
我有一个单元测试正在运行以计算写入的记录,并读取输出的文件以进行仔细检查。
失败:
var tasks = new List<Task>();
Parallel.ForEach(File.ReadLines(featuresLocation), s =>
{
var feature = CreateFeature(s);
if (feature.HasValue)
{
tasks.Add(Task.Factory.StartNew(() =>
{
lock (_locker)
{
featuresWriter.WriteLine(feature.Value);
RecordsWrote++;
}
}));
}
});
Task.WaitAll(tasks.ToArray()); // Breaks
Run Code Online (Sandbox Code Playgroud)
在职的:
var tasks = new List<Task>();
Parallel.ForEach(File.ReadLines(featuresLocation), s =>
{
var feature = CreateFeature(s);
if (feature.HasValue)
{
tasks.Add(Task.Factory.StartNew(() =>
{
lock (_locker)
{
featuresWriter.WriteLine(feature.Value);
RecordsWrote++;
}
}));
}
});
Task.WaitAll(tasks.Where(x => x != null).ToArray()); // Works
Run Code Online (Sandbox Code Playgroud) 给定一个包含 Urls 的输入文本文件,我想一次下载相应的文件。我使用这个问题UserState的答案 使用 WebClient 和 TaskAsync 从 Async CTP 下载作为参考。
public void Run()
{
List<string> urls = File.ReadAllLines(@"c:/temp/Input/input.txt").ToList();
int index = 0;
Task[] tasks = new Task[urls.Count()];
foreach (string url in urls)
{
WebClient wc = new WebClient();
string path = string.Format("{0}image-{1}.jpg", @"c:/temp/Output/", index+1);
Task downloadTask = wc.DownloadFileTaskAsync(new Uri(url), path);
Task outputTask = downloadTask.ContinueWith(t => Output(path));
tasks[index] = outputTask;
}
Console.WriteLine("Start now");
Task.WhenAll(tasks);
Console.WriteLine("Done");
}
public void Output(string path)
{
Console.WriteLine(path);
}
Run Code Online (Sandbox Code Playgroud)
我预计文件的下载将在“Task.WhenAll(tasks)”点开始。但事实证明,输出看起来像
c:/temp/Output/image-2.jpg c:/temp/Output/image-1.jpg c:/temp/Output/image-4.jpg …
我想在包含操作的任务中添加多个参数。我查看了现有的堆栈溢出问题Create a Task with an Action<T>
请帮助我如何在任务的 Action 方法中传递多个参数
Action<string, int> action = (string msg, int count) =>
{
Task.Factory.StartNew(async () =>
{ await LoadAsync(msg, count); });
};
Task task = new Task(action, ....);
Run Code Online (Sandbox Code Playgroud)
动作方法是
public static async Task<string> LoadAsync(string message, int count)
{
await Task.Run(() => { Thread.Sleep(1500); });
Console.WriteLine("{0} {1} Exceuted Successfully !", message ?? string.Empty, (count == 0) ? string.Empty : count.ToString());
return "Finished";
}
Run Code Online (Sandbox Code Playgroud)
请帮助我如何创建异步方法的操作以及如何将操作添加到任务中。
考虑一个带有 2 个按钮和一个富文本框的表单:
public partial class MainForm : Form
{
CancellationTokenSource cts;
CancellationToken token;
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
cts = new CancellationTokenSource();
token = cts.Token;
var task = Task.Run(() => WriteSomeLines(), token);
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
cts.Dispose();
}
private void btnStart_Click(object sender, EventArgs e)
{
cts = new CancellationTokenSource();
token = cts.Token;
var task = Task.Run(() => WriteSomeLines(), token);
}
private void btnCancel_Click(object sender, EventArgs e)
{
try …Run Code Online (Sandbox Code Playgroud) 在以下代码中:
if (await Task.WhenAny(task, Task.Delay(100)) == task) {
success = true;
}
else {
details += "Timed out on SendGrid.";
await task.ContinueWith(s =>
{
LogError(s.Exception);
}, TaskContinuationOptions.OnlyOnFaulted);
}
Run Code Online (Sandbox Code Playgroud)
我偶尔会A task was cancelled接到电话await task.ContinueWith.我的目标是看看是否task在100ms内完成 - 如果没有,我想处理一些日志记录(这个特定任务有资源泄漏,所以我试图通过将其包装在超时中来解决它).这是从这里的指导中提取的: Debugging Task.WhenAny和Push Notifications
为什么会发生这种情况,我该怎么做才能防止抛出此异常?
我有一个脚本可以生成数百万个 Celery 任务,数据库中每行一个。有没有办法限制它,使其不会完全淹没芹菜?
理想情况下,我想让 Celery 保持忙碌,但我不希望 Celery 队列的长度超过几十个任务,因为这只是浪费内存(特别是因为没有某种限制,脚本会将数百万个任务添加到几乎立即排队)。
我遇到了以下使用 ContinueWith() 等待结果的代码。
public async Task<User> GetUser()
{
return await _serviceRepo.GetUserAsync()
.ContinueWith(task =>
{
return task.Result;
});
}
Run Code Online (Sandbox Code Playgroud)
是否ContinueWith()阻塞调用线程直到任务从GetUserAsync()调用返回?
由于 位于task.Result已安排的 ContinueWith() 内,在等待前件时task是否有任何内容被阻止?
我在其他几个地方看到过这种类型的代码,这被认为是异步/等待模式的最佳实践吗?我希望GetUserAsync()调用返回结果而不是使用 aContinueWith()来等待它。
我想使用 CancellationTokenSource 停止任务。我的测试如下:
测试 1:使用 Cancel() 成功停止了任务。
测试 2:使用 CancelAfter() 没有停止任务,为什么?
任务动作是:
static Action testFun = () => {
Thread.Sleep(4000); // or other a long time operation
Console.WriteLine("Action is end");
};
Run Code Online (Sandbox Code Playgroud)
测试1代码:
CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token = source.Token;
//Register the cancel action
token.Register(() =>
{
Console.WriteLine("Task is canceled");
});
Task task = new Task(testFun, token);
task.Start();
source.Cancel();
Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)
输出是:
Task is canceled
Run Code Online (Sandbox Code Playgroud)
测试2代码:
CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token = source.Token;
//Register the cancel action
token.Register(() …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个运行带有一些参数的命令的 VSCode 任务。
"tasks": [
{
"label": "Execute in Max",
"type": "shell",
"command": "cd\\; C:\\MXSPyCOM.exe",
"args": [
"-f",
"'${file}'"
],
"problemMatcher": []
}
]
Run Code Online (Sandbox Code Playgroud)
从那我得到错误:
& : 无法加载模块“cd”。有关更多信息,请运行“Import-Module cd”。在行:1 字符:3 + & 'cd\; C:\MXSPyCOM.exe' -f 'c:\Users\ ... + ~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (cd\; C:\MXSPyCOM.exe:String) [], CommandNotFoundException +fullyQualifiedErrorId : couldNotAutoLoadModule
我相当肯定问题是它试图执行'cd\; C:\MXSPyCOM.exe' -f 'c:\Users\的命令:主命令块出于某种原因用单引号括起来,这使得 shell 认为它是一个命令,当它是多个命令时。
这过去没有发生过,几个月前我上次使用它时,这个确切的命令工作得很好。知道有什么问题吗?
When reading
How to: Create Pre-Computed Tasks
the example method DownloadStringAsync returns
Task.Run( async ()=> { return await new WebClient().DownloadStringTaskAsync(address)})
Run Code Online (Sandbox Code Playgroud)
I wonder why we need to wrap a async method in a Task.Run()? the WebClient().DownloadStringTaskAsync() method returns a Task itself.
task ×10
c# ×8
async-await ×2
asynchronous ×2
.net ×1
c#-4.0 ×1
celery ×1
continuewith ×1
delegates ×1
python ×1
queue ×1
taskfactory ×1
webclient ×1