如何单元测试具有等待Task.Delay的组件,而不必等待它.
例如,
public void Retry()
{
// doSomething();
if(fail)
await Task.Delay(5000);
}
Run Code Online (Sandbox Code Playgroud)
我需要测试失败分支,但我不希望我的测试等待5秒.
在任务并行库中是否有类似rx虚拟时间调度的功能?
tdd unit-testing task-parallel-library system.reactive async-await
我有一个同步方法,除其他外,它检查挂起任务的状态并重新抛出其异常,如果有的话:
void Test(Task task)
{
// ...
if (task.IsFaulted)
throw task.Exception;
// ...
}
Run Code Online (Sandbox Code Playgroud)
这不会传播异常堆栈跟踪信息,并且对调试器不友好.
现在,如果Test是async,它将不会像这样简单和自然:
async Task Test(Task task)
{
// ...
if (task.IsFaulted)
await task; // rethrow immediately and correctly
// ...
}
Run Code Online (Sandbox Code Playgroud)
问题:如何正确执行同步方法?我想出了这个,但我不喜欢它:
void Test(Task task)
{
// ...
if (task.IsFaulted)
new Action(async () => await task)();
// ...
}
Run Code Online (Sandbox Code Playgroud) 使用TPL Dataflow库,我想做这样的事情:
myActionBlock.Post(newValue, cancelAllPreviousPosts: true);
Run Code Online (Sandbox Code Playgroud)
似乎ActionBlock上的取消令牌取消了整个事情; 如果我设置了那个,我必须创建一个新的ActionBlock.是否可以使用ActionBlock进行部分取消?
尚未尝试尚未处理的帖子.如果有一些取消令牌可用于检查当前正在执行的帖子,那将是很好的.
c# task-parallel-library cancellationtokensource tpl-dataflow
标题说明了一切.有什么不对await Task.Run(() => semaphore.WaitOne());吗?System.Threading.Semaphore不是线程仿射,所以我不认为会有问题.我知道这个SemaphoreSlim类是可用的,但是我需要进行跨进程同步,而SemaphoreSlim不是那样做.
或者我可以/应该创建自己的自定义类型WaitHandle吗?
背景:
我有一个服务,它聚合来自多个其他服务的数据.为了使事情及时发生,我在整个代码中使用异步,然后将各种请求收集到任务列表中.
以下是代码的一些摘录:
private async Task<List<Foo>> Baz(..., int timeout)
{
var tasks = new List<Task<IEnumerable<Foo>>>();
Tasks.Add(GetFoo1(..., timeout));
Tasks.Add(GetFoo2(..., timeout));
// Up to 6, depending on other parameters. Some tasks return multiple objects.
return await Task.WhenAll(tasks).ContinueWith((antecedent) => { return antecedent.Result.AsEnumerable().SelectMany(f => f).ToList(); }).ConfigureAwait(false);
}
private async Task<IEnumerable<Foo>> GetFoo1(..., int timeout)
{
Stopwatch sw = new Stopwatch();
sw.Start();
var value = await SomeAsyncronousService.GetAsync(..., timeout).ConfigureAwait(false);
sw.Stop();
// Record timing...
return new[] { new Foo(..., value) };
}
private async Task<IEnumerable<Foo>> GetFoo2(..., int timeout) …Run Code Online (Sandbox Code Playgroud) 当在工作线程上调用的方法需要在UI线程上运行代码并在执行其他操作之前等待它完成时,可以这样做:
public int RunOnUi(Func<int> f)
{
int res = Application.Current.Dispatcher.Invoke(f);
return res;
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我想用任务做什么呢?有没有办法让RunOnUi方法创建一个在UI上启动并返回它的任务,以便调用者(在工作线程上运行)可以等待它?符合以下签名的东西:public Task<int> StartOnUi(Func<int> f)?
一种方法如下:
public Task<int> RunOnUi(Func<int> f)
{
var task = new Task<int>(f);
task.Start(_scheduler);
return task;
}
Run Code Online (Sandbox Code Playgroud)
这里,假设_schduler持有ui TaskScheduler.但是我不太习惯于创建"冷"任务并使用start方法来运行它们.这是"推荐"的方式还是有更优雅的方式来做到这一点?
代码示例:
using System;
using System.Threading.Tasks;
public class Program
{
public static void Main()
{
Console.WriteLine("Start");
Foo f = new Foo();
f.FooAsync();
}
public class Foo
{
public async void FooAsync()
{
try
{
await Task.Run(() =>
{
Console.WriteLine("Throwing");
throw new Exception();
});
}
catch (Exception)
{
Console.WriteLine("Caught");
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码从C#小提琴或从我的PC上的控制台运行时打印:
Start
Throwing
Caught
Run Code Online (Sandbox Code Playgroud)
但是,当我从Visual Studio(调试模式下的F5)运行它时,我收到以下消息:

我不明白为什么我从Visual Studio得到"没有在用户代码中处理"消息,尽管从控制台或C#小提琴运行它是好的.我错过了一些明显的东西吗
UPDATE
我已经尝试f.FooAsync().Wait();在Main中等待任务,但仍然报告异常未处理(相同的错误消息).
我正在使用C#/ Xaml开发Windows 10 Universal App,我正在使用等待Task.Delay(delayInMilliseconds)来暂停给定时间的方法.我的场景有点实时,因此它对时间变化非常敏感,我需要确保当我暂停一个方法让我们说8毫秒时,它会暂停8毫秒.我注意到**Task.Delay**暂停方法的实际时间跨度与传递的延迟参数不同,1到30毫秒,每次调用的"偏差"长度不同.所以,当我想睡8毫秒时,我的系统会睡眠9到39毫秒,这完全破坏了我的情景.所以,我的问题是什么是替换**Task.Delay**并获得良好精度的最佳方法?目前我使用这种方法:
public static void Delay1(int delay)
{
long mt = delay * TimeSpan.TicksPerMillisecond;
Stopwatch s = Stopwatch.StarNew();
while (true)
{
if (s.Elapsed.TotalMilliseconds > delay)
{
return;
}
}
}
Run Code Online (Sandbox Code Playgroud)
但它猜测它消耗了大量资源,即处理器核心的100%.如果用户具有少量处理器核心,则这将是非常不足的.
我正在使用Db(通过SQLite.NET PCL,而不是异步版本).在目前我有一个列表视图与一些数据(取自数据库),我也有一个搜索栏/条目(其nvm),用户可以输入一些值然后,通过LINQ我将进行查询并更新SourceItems我的清单.
所以问题来自于性能,因为我的数据库有百万条记录和简单的LINQ查询工作非常慢.换句话说,当用户输入的数据太快时,应用程序会有很大的滞后,有时会崩溃.
为了解决这个问题,我想到了一些事情(理论上的解决方案):
1)需要在任务上放置方法(我对db进行查询)(解锁我的主UI线程)
2)初始化计时器,然后打开并:
类似的东西(类似)或任何建议.谢谢!
UPD:
说实话,我尝试了太多并没有得到好结果
BTW,我目前的代码(片段):
1)我的SearchMethod
public void QueryToDB(string filter)
{
this.BeginRefresh ();
if (string.IsNullOrWhiteSpace (filter))
{
this.ItemsSource = SourceData.Select(x => x.name); // Source data is my default List of items
}
else
{
var t = App.DB_Instance.FilterWords<Words>(filter); //FilterWords it's a method,where i make direct requests to the database
this.ItemsSource = t.Select(x => x.name);
}
this.EndRefresh …Run Code Online (Sandbox Code Playgroud) c# multithreading search-engine task-parallel-library xamarin.forms
我已经阅读了这个主题,该主题声称参考msdn并认为async/await不会创建新线程.请看下面的代码:
static class Program
{
static void Main(string[] args)
{
var task = SlowThreadAsync();
for(int i = 0; i < 5; i++)
{
Console.WriteLine(i * i);
}
Console.WriteLine("Slow thread result {0}", task.Result);
Console.WriteLine("Main finished on thread {0}", Thread.CurrentThread.ManagedThreadId);
Console.ReadKey();
}
static async Task<int> SlowThreadAsync()
{
Console.WriteLine("SlowThreadAsync started on thread {0}", Thread.CurrentThread.ManagedThreadId);
await Task.Delay(2000);
Console.WriteLine("SlowThreadAsync completed on thread {0}", Thread.CurrentThread.ManagedThreadId);
return 3443;
}
}
Run Code Online (Sandbox Code Playgroud)
由于这段代码我得到了不同的ThreadId.为什么同一个线程获得不同的ThreadId?
c# multithreading asynchronous task-parallel-library async-await
c# ×8
async-await ×5
.net ×3
asynchronous ×1
task ×1
tdd ×1
tpl-dataflow ×1
unit-testing ×1
wpf ×1