实体框架取消长时间运行的查询。

3
我是TPL的新手。我正在使用TPL对数据库进行一些异步调用。下面的GetDocumentAsync方法被多次调用,很好地将任务卸载到不同的线程中,以保持UI线程的响应性。
这里有两个目标:1)保持UI线程的响应 2)让用户能够中止请求。
我已经成功中止了请求,但我无法中止Entity Framework已经放到数据库中并且查询正在数据库层面上运行(或者甚至还没有开始)的请求。因此,GetDocuments方法仍然返回已取消任务的文档。
是否有办法从EF中中止请求?我的实现中是否可以做得更好?
    Entities _context = new Entities();

    CancellationTokenSource _tokenSource = new CancellationTokenSource();

    public async void GetDocumentsAsync(string userName)
    {
        IList<Document> results;
        try
        {
            results = await 
            Task<List<Document>>.Factory.StartNew(() =>
            {
                _tokenSource.Token.ThrowIfCancellationRequested();
                return GetDocuments(userName);
            }, _tokenSource);

        }
        catch (OperationCanceledException ex)
        {
            Debug.WriteLine(string.Format("Task canceled for user {0} on thread", userName ));
        }

        if(!_tokenSource.IsCancellationRequested)
        {
            // results is used to update the UI 
        }
    }

    public void Abort()
    {
        _tokenSource.Cancel();
    }

    public List<Document> GetDocuments(string userName)
    {
        //I am using the connected model and need to use the Context for change tracking and other goodies..
        var query = from c in _context.Documents
                    where c.CreatedBy == userName
                    select c;

        query = query.Take(50); // I want to be able to cancel this query. Can this be done ???

        return query.ToList();
    }
1个回答

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接