我正在努力使用正确的方法来模拟和设置一个返回普通(即非泛型)的方法的期望Task.假设我有一个ICanNotCode使用以下方法调用的接口:
async Task DoSomethingIncredible();
Run Code Online (Sandbox Code Playgroud)
我正在使用Rhino Mocks作为我的模拟框架,并且一直在尝试为使用此接口的单独方法编写测试.期望看起来像这样:
canNotCodeMock.Expect(mock => mock.DoSomethingIncredible()).Return(new Task(() => { }));
Run Code Online (Sandbox Code Playgroud)
代码编译,但每当我运行Visual Studio时,它就会挂起,直到我手动终止任务运行器.
对返回方法设定期望的正确方法是Task什么?非常感谢你的帮助!
我不确定我应该如何混合plinq和async-await.假设我有以下界面
public interface IDoSomething (
Task Do();
}
Run Code Online (Sandbox Code Playgroud)
我有一个列表,我想并行执行,并能够await完成所有这些.
public async Task DoAll(IDoSomething[] doers) {
//Execute all doers in parallel ideally using plinq and
//continue when all are complete
}
Run Code Online (Sandbox Code Playgroud)
怎么实现这个?我不知道如何从并行linq转到任务,反之亦然.
我对异常处理并不十分担心.理想情况下,第一个会触发并打破整个过程,因为我打算在出错时抛弃整个过程.
编辑:很多人都说Task.WaitAll.我知道这一点,但我的理解(除非有人能证明不是这样)是因为它不能主动将你的东西并行化到多个可用的处理器核心.我特别要问的是双重的 -
如果我await一个Task一个PLINQ行动中确实是摆脱由于日程安排一个新的线程有很多的优势的?
如果我doers.AsParallel().ForAll(async d => await d.Do())平均需要大约5秒钟,那么在此期间我怎么不旋转调用线程呢?
c# linq parallel-extensions task-parallel-library async-await
鉴于此代码:
s_Batch = new BatchBlock<PerformanceRecord>(500);
s_Action = new ActionBlock<PerformanceRecord[]>(a => SendToDatabase(a));
s_Batch.LinkTo(s_Action);
Run Code Online (Sandbox Code Playgroud)
当我完成后,我需要打电话Complete()给每个街区吗?或者将完成s_Batch触发链接到它的块中的完整?
我正在尝试使用.ToListAsync()Inside a DbContext的using语句获取linq查询结果,代码:
private async Task<List<String>> GetEntiteesAsync()
{
Task<List<String>> returnValue;
using (var entities = new REPORTEntities())
{
returnValue = (from user in entities.USERs
group user by user.entite into g
select g.Key).ToListAsync();
}
return await returnValue;
}
Run Code Online (Sandbox Code Playgroud)
在运行时,我得到"已经处理了ObjectContext实例,不能再用于需要连接的操作." 如图所示 :

我认为这是由于在returnValue对象仍然像List一样异步接收对象的情况下处理Context这一事实引起的,是否有一种解决方法可以在保留using语句时避免此错误,或者我应该这样做:
private async Task<List<String>> GetEntiteesAsync()
{
Task<List<String>> returnValue;
var entities = new REPORTEntities()
returnValue = (from user in entities.USERs
group user by user.entite into g
select g.Key).ToListAsync();
return await returnValue;
}
Run Code Online (Sandbox Code Playgroud) 我有一个控制器操作,它获取文档类型列表,然后为每个文档类型进行Web服务调用.我想立刻制作这些,所以循环它们只需要最长的一个.我不知道我的代码是否正确,我还需要做其他事情,或者我的代码是不正确的.
行动:
public ActionResult GetPlan(MemberViewModel request)
{
DocService ds = new DocService();
List<DocType> docTypes = ds.GetDocTypesForPlan(request.PlanId);
List<CoverageDocument> coverageDocuments = ds.GetDocumentsForDocTypes(docTypes);
return View(coverageDocuments);
}
Run Code Online (Sandbox Code Playgroud)
GetDocumentsForDocTypes:
public List<CoverageDocument> GetDocumentsForDocTypes(List<DocType> planDocTypes)
{
List<CoverageDocument> planDocuments = new List<CoverageDocument>();
DocumentUtility documentUtility = new DocumentUtility();
int lastYear = DateTime.Now.Year - 1;
planDocTypes.ForEach(async (docType) =>
{
DocumentUtility.SearchCriteria sc = new DocumentUtility.SearchCriteria();
sc.documentType = docType;
Dictionary<long, Tuple<string, string>> documentList = await documentUtility.FindDocuments(sc);
documentList.ToList().ForEach((document) =>
{
CoverageDocument doc = this.coverageDocumentConstructor(document);
planDocuments.Add(doc);
});
});
return planDocuments;
}
Run Code Online (Sandbox Code Playgroud)
例外:
附加信息:此时无法启动异步操作.异步操作只能在异步处理程序或模块中启动,或者在页面生命周期中的某些事件中启动.如果在执行页面时发生此异常,请确保将页面标记为<%@ Page …
我有一个async功能.有多个级别的函数调用都返回a Task.在这个链中的某个点上,我必须修改结果的值.我想这样做而不会中断async函数的流程.注意:
[HttpGet]
[Route("GetWeb")]
public async Task<IHttpActionResult> GetResult([FromUri] string url)
{
var result = await GetPageText(url);
return Ok(result);
}
private Task<string> GetPageText(string url)
{
Task<string> data = GetDataAsync(url);
//here I would like to manipulate the data variable
return data;
}
Run Code Online (Sandbox Code Playgroud)
在该函数中,GetPageText如何在不中断异步流的情况下操作数据变量.这可能吗?
我需要使用一个提供对自己数据库的访问的库.不幸的是,所有方法都是经典同步.我宁愿有async方法来卸载IO负载,就像我们已经说过的SQL Server一样.
我知道这是一个非常通用的问题,没有太多具体信息.有没有办法移动到那一点,还是太糟糕了?
非常感谢示例和/或链接.
我的数据有以下结构
public enum ParamType
{
Integer=1,
String=2,
Boolean=3,
Double=4
}
public class Gateway
{
public int _id { get; set; }
public string SerialNumber { get; set; }
public List<Device> Devices { get; set; }
}
public class Device
{
public string DeviceName { get; set; }
public List<Parameter> Parameters { get; set; }
}
public class Parameter
{
public string ParamName { get; set; }
public ParamType ParamType { get; set; }
public string Value { get; set; } …Run Code Online (Sandbox Code Playgroud) 您好我有以下代码创建任务.然后将其设置为开始.该任务旨在添加对ConcurrentBag列表的响应.但等待似乎并不等待完成所有任务.但他们被标记为已完成.列表中只有一个任务.使用时效果很好Task.Run!
public async void RunT1()
{
DoesNotWork();
}
public async void RunT2()
{
DoesWork();
}
public async void DoesNotWork()
{
ConcurrentBag<string> concurrentBag = new ConcurrentBag<string>();
List<Task> taskList = new List<Task>();
Task task1 = new Task(async () =>
{
var xml = await LongWorkingMethod();
concurrentBag.Add(xml);
});
taskList.Add(task1);
taskList[0].Start();
await Task.WhenAll(taskList);
if (concurrentBag.Count > 0)//concurrentBag is empty even though the task has finished
{
Debug.Print("success");
}
}
public async void DoesWork()
{
ConcurrentBag<string> concurrentBag = new ConcurrentBag<string>();
List<Task> …Run Code Online (Sandbox Code Playgroud) 我正在使用parse.com进行身份验证.当用户通过身份验证时,我想从解析中加载一些数据,但这只应在身份验证成功时进行.我尝试用a取消任务CancellationToken,但它不起作用.这是示例代码:
CancellationTokenSource cts = new CancellationTokenSource();
ParseUser.LogInAsync(username, password).ContinueWith(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
// Login failed
cts.Cancel();
}
return t;
}, cts.Token).Unwrap().ContinueWith(t =>
{
return LoadDataAsync();
}).Unwrap().ContinueWith(t =>
{
LoginSuccessful();
})
Run Code Online (Sandbox Code Playgroud)
可以取消这样的任务吗?或者我做错了什么?
c# ×10
.net ×8
async-await ×7
asynchronous ×2
linq ×2
asp.net-mvc ×1
io ×1
mongodb ×1
rhino-mocks ×1
tpl-dataflow ×1
unit-testing ×1