标签: asynchronous

将此代码转换为任务以在另一个线程上异步运行

我开始玩任务和异步等待.为了更好地处理如何转换现有代码,我想我会尝试更改同步运行的当前方法:

private bool PutFile(FileStream source, string destRemoteFilename, bool overwrite)
{
    if (string.IsNullOrEmpty(destRemoteFilename)) return false;
    string path = Path.GetDirectoryName(destRemoteFilename);
    if (path == null) return false;
    if (!Directory.Exists(path)) Directory.CreateDirectory(path);
    if (overwrite)
    {
        if (File.Exists(destRemoteFilename)) //delete file if it exists, because we are going to write a new one                 File.Delete(destRemoteFilename);
    }
    else if (File.Exists(destRemoteFilename)) return false;
    using (FileStream dest = File.OpenWrite(destRemoteFilename))
    {
        source.Seek(0, SeekOrigin.Begin);
        source.CopyTo(dest);
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)

我试图简单地改变方法async,并且涉及Task<bool>但我显然在这里遗漏了一些东西,因为它们似乎都不起作用.我经历过的Type System.Threading.Task<bool>是不值得期待的.

c# multithreading asynchronous task

0
推荐指数
1
解决办法
1241
查看次数

使用node.js异步系列,但不起作用

我想使用async使node.js按顺序工作,首先从mongodb查询两个速率,然后使用这些速率计算两个新速率:

async.series([
    function(callback){
        db.collection('heros',function(err,collection){
            if(err){
                console.log(err);
            }
            if(!err){
                console.log("2 collection fetched!");
                collection.findOne({'id':win},function(err,result){
                    if (err) throw err;
                    rate1=result.rate;
                    console.log("win-rate:"+rate1);
                });
                collection.findOne({'id':lose},function(err,result){
                    if (err) throw err;
                    rate2=result.rate;
                    console.log("lose-rate:"+rate2);
                });         
            }
        });
        callback(null);

    }, function(callback){   
        var Ea= 1/(1+Math.pow(10,(rate2-rate1)/400));
        var Eb= 1/(1+Math.pow(10,(rate1-rate2)/400));
        var ra= rate1+16*(1-Ea);
        var rb= rate2+16*(0-Eb);
        console.log("ra:"+ra);
        console.log("rb:"+rb);
        callback(null);
    },
        function(callback){   
    db.collection('heros',function(err,collection){
        if(!err){
        collection.update({'id':win},{$set:    {rate:ra}},function(err,result){
          if(err) throw err;
          if(!err){
            console.log("update successful");
          }
          });
          collection.update({'id':lose},{$set:{rate:rb}},function(err,result){
          if(err) throw err;
          if(!err){
            console.log("update successful");
        }
        });

            }

    });
    callback(null);
}
]);
Run Code Online (Sandbox Code Playgroud)

但是当我运行它时,它会显示错误消息:

async.series([
    function(callback){
        db.collection('heros',function(err,collection){
            if(err){ …
Run Code Online (Sandbox Code Playgroud)

asynchronous node.js

0
推荐指数
1
解决办法
1380
查看次数

jQuery mobile:等到$ .getJSON完成

我想通过$.getJSON调用填充表格:

$.getJSON("localhost/url",
function (data) {
    $.each(data.reporting_list.reporting, function (i, item) {
        rows = '<tr><td>' + item.data1 + '</td><td>' + item.data2 + '</td></tr>'
    });
    $('#aaa').append(rows);
});
Run Code Online (Sandbox Code Playgroud)

填充后我想激活一些页面更改:

$.mobile.changePage("#homePage");
Run Code Online (Sandbox Code Playgroud)

但页面在$.getJSON完成之前发生了变化.
我想在$.getJSON完成后更改页面并改为显示ajaxloader.

jquery json asynchronous jquery-callback jquery-mobile

0
推荐指数
1
解决办法
6736
查看次数

使用异步任务调用同步WCF服务

我有一个由服务客户端调用的WCF服务.我想使用async/await构造来包装对此的调用; 但是,服务和服务客户​​端是.NET3.5.我对此的解决方案如下:

private async Task<ObservableCollection<MyEntity>> LoadData(ParamData param)
{
        ServiceClient svc = new ServiceClient();
        int results = 0;

        // Set-up parameters
        myParams = BuildParams(param);

        // Call a count function to see how much data we're talking about
        // This call should be relatively quick
        var counter = Task.Factory.StartNew(() =>
        {
            results = svc.GetResultCount(myParams);
        }).ContinueWith((task) =>
        {
            if (results <= 10000 ||
                (MessageBox.Show("More than 10000 results, still retrieve data?"), MessageBoxButton.YesNo) == MessageBoxResult .Yes))
            {
                return svc.Search(myParams);
            }
        });
}
Run Code Online (Sandbox Code Playgroud)

我收到编译错误:

Since 'System.Action<System.Threading.Tasks.Task>' …
Run Code Online (Sandbox Code Playgroud)

c# wcf asynchronous async-await .net-4.5

0
推荐指数
1
解决办法
5882
查看次数

asyncjs - eachSeries()不迭代数组中的所有项

我有以下代码使用async.js

var async = require('async');
var A = [];

for(var i = 1; i < 100; i++)
    A.push(i);

async.eachSeries(A, function(item) {
    console.log(item);
});
Run Code Online (Sandbox Code Playgroud)

我希望这能打印从1到100的数字,但是当我运行它时,输出就是 1

但是,如果我使用each()而不是eachSeries()它打印所有数字.

那么,为什么代码不工作而eachSeries()只是一个串行版本each()

asynchronous node.js async.js

0
推荐指数
1
解决办法
2080
查看次数

Foreach循环进入下一次迭代,无需waitng进行当前迭代

在foreach循环中我调用一个方法:

for (Iterable pl : ilist) {

myMethod();

}
Run Code Online (Sandbox Code Playgroud)

myMethod()可能需要很长时间才能当前(比如几分钟或几天)p1对象,但是执行时我想继续进行下一次迭代.(据我所知,这可以称为异步调用)

甚至可以使用foreach循环吗?

java methods foreach asynchronous

0
推荐指数
1
解决办法
1194
查看次数

Meteor.methods:从内部回调将数据返回给客户端

我尝试通过Meteor服务器从LDAP服务器获取数据到客户端.但是LDAP-Request是异步的,并且该方法返回false,而不是在ldap.search函数调用中收集的结果.那么,当数据准备就绪时,如何同步调用ldap或在客户端触发事件?

  //defined on serverside
  Meteor.methods({
    searchPerson: function(account){
      var data = null;
      var LDAP = Npm.require('LDAP');
      var ldap = new LDAP({uri: 'ldaps://ldap-server', version: 3});

      var search_options = { 
        base: 'ou=xxx,dc=yyy,dc=zzz',
        scope: '1',
        filter: '(uid='+account+')',
        attrs: 'surname, givenname, mail'
      };  
      var bind_options = { 
        binddn:   'cn=aaa,ou=bbb,dc=ccc,dc=ddd', 
        password: 'password'
      };  

      ldap.open(function(err) {
        if (err) {
          throw new Meteor.Error('Can not connect');
        }   
        ldap.simpleBind(bind_options, function(err){
          if (err){
            throw new Meteor.Error('Can not bind');
          }   
          ldap.search(search_options, function(err, data){
            if (err){
              throw new Meteor.Error('Error occured');
            }   
            return data; …
Run Code Online (Sandbox Code Playgroud)

javascript asynchronous meteor

0
推荐指数
1
解决办法
1534
查看次数

长时间运行的文件操作和执行超时

我被要求为我工作的组织编写一个文档管理系统,它提供了一系列与不同记录相关的九个不同的工作流程.其中的工作流程是将文档添加到"文件"或记录中,并根据业务规则将这些文档的子集发布到公共网站.

这些文件几乎无一例外地以PDF格式存在,并且通常在任何一个记录中,在任何一个时间处理的文件少于二十个.

将此作为Web应用程序构建的主要原因是将文件保留在我们的数据中心和高速交换机上,而不是通过远程站点上可能较慢的连接速度来尝试在位置之间复制和备份.

该系统运行良好,直到更大系列的文件(114个PDF文件,大小总共329MB)超过95%的时间.

代码是(IncomingDocuments类型为List <FileInfo>) -

List<string> filesSuccessfullyAdded = new List<string>();

foreach (FileInfo incomingFile in IncomingDocuments)
{
    FileOperations.AddDocument(incomingFile, false, ApplicationCode, (targetDirectoryPath.EndsWith(@"\") ? targetDirectoryPath : targetDirectoryPath + @"\"));
    FileInfo copiedDocument = new FileInfo(Path.Combine(targetDirectoryPath, incomingFile.Name));
    if (copiedDocument.Exists && copiedDocument.Length == incomingFile.Length && copiedDocument.LastWriteTime == incomingFile.LastWriteTime)
    {
        filesSuccessfullyAdded.Add(copiedDocument.Name);
    }
}

if (filesSuccessfullyAdded.Any())
{
    SetupConfirmationLiteral.Text += "<p class='info'>The following files have been successfully added to the application file-</p>";

    XDocument successfullyAddedList = new XDocument(
    new XElement("ul", new XAttribute("class", "documentList")));

    foreach (string successfulFile in filesSuccessfullyAdded) …
Run Code Online (Sandbox Code Playgroud)

c# asp.net asynchronous timeout webforms

-1
推荐指数
1
解决办法
1214
查看次数

关于异步编程与异步和等待c#的问题

我正在学习如何使用Async和Await c#.所以我有一个链接http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx#BKMK_WhatHappensUnderstandinganAsyncMethod

从这里我尝试从VS2012 IDE运行代码,但收到错误.此功能引发错误.

private void button1_Click(object sender, EventArgs e)
        {
            int contentLength = await AccessTheWebAsync();

            label1.Text= String.Format("\r\nLength of the downloaded string: {0}.\r\n", contentLength);
        }
Run Code Online (Sandbox Code Playgroud)

此行给出错误await AccessTheWebAsync(); 'await'运算符只能在异步方法中使用.考虑使用'async'修饰符标记此方法并将其返回类型更改为'Task'

我做错了什么.请指导我如何运行代码.谢谢

c# asynchronous async-await

-1
推荐指数
1
解决办法
664
查看次数

异步比同步慢

我一直在进行异步调用,发现方法的异步版本比同步版本运行慢得多。谁能评论我可能缺少的东西。谢谢。

统计

同步方法时间为00:00:23.5673480

异步方法时间为00:01:07.1628415

每个呼叫返回的总记录/条目= 19972

下面是我正在运行的代码。

--------------------测试课程----------------------

[TestMethod]
public void TestPeoplePerformanceSyncVsAsync()
{
    DateTime start;
    DateTime end;

    start = DateTime.Now;
    for (int i = 0; i < 10; i++)
    {
    using (IPersonRepository repository = kernel.Get<IPersonRepository>())
    {
        IList<IPerson> people1 = repository.GetPeople();
        IList<IPerson> people2 = repository.GetPeople();
    }
    }
    end = DateTime.Now;
    var diff = start - end;
    Console.WriteLine(diff);

    start = DateTime.Now;
    for (int i = 0; i < 10; i++)
    {
    using (IPersonRepository repository = kernel.Get<IPersonRepository>())
    {
        Task<IList<IPerson>> people1 = GetPeopleAsync();
        Task<IList<IPerson>> …
Run Code Online (Sandbox Code Playgroud)

c# asynchronous task-parallel-library async-await .net-4.5

-1
推荐指数
1
解决办法
1533
查看次数