小编i3a*_*non的帖子

如何更改任务中的值

我有一个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如何在不中断异步流的情况下操作数据变量.这可能吗?

.net c# asynchronous async-await asp.net-web-api

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

如何在C#中围绕第三方IO库编写异步包装器

我需要使用一个提供对自己数据库的访问的库.不幸的是,所有方法都是经典同步.我宁愿有async方法来卸载IO负载,就像我们已经说过的SQL Server一样.

我知道这是一个非常通用的问题,没有太多具体信息.有没有办法移动到那一点,还是太糟糕了?

非常感谢示例和/或链接.

.net c# io async-await

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

MongoDB无法确定表达式错误的序列化信息

我的数据有以下结构

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)

.net c# mongodb mongodb-.net-driver

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

Task.Start奇怪的行为

您好我有以下代码创建任务.然后将其设置为开始.该任务旨在添加对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)

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

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

有没有办法在异步方法中使用out参数.?如果没有,任何人都可以建议我如何从异步方法返回OUT参数?

我使用以下方法:

public async Task<SaveStatus> Save(Foo foo,out int param)
{
    .......
    MySqlParameter prmparamID = new MySqlParameter("pParamID", MySqlDbType.Int32);
        prmparamID .Direction = ParameterDirection.Output;
        sqlCommand.Parameters.Add(prmparamID); 
    try
        {
            await sqlConnection.OpenAsync();
            await sqlCommand.ExecuteNonQueryAsync();

            status = (SaveStatus)Convert.ToInt32(prmReturnValue.Value);

            if (status == SaveStatus.Success)
            {
                if (Common.IsDBValueNotNullOrEmpty(prmParamID))
                {
                    param= Convert.ToInt32(prmParamID.Value);
                }
            }
        }      

    return status;
}
Run Code Online (Sandbox Code Playgroud)

我想返回状态和整数参数.任何人都可以帮我解决这个问题吗?

.net c# task-parallel-library async-await asp.net-web-api2

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

async等待一个简单的包装器方法

如果我编写一个只包装异步方法的方法,例如:

public async Task WrapMethodAsync()
{
    using(var smtpClient = new SmtpClient())
    {
        await smtpClient.SendMailAysnc(new MailMessage());
    }
}
Run Code Online (Sandbox Code Playgroud)

这与执行以下操作相同:

public Task WrapMethodAsync()
{
    using(var smtpClient = new SmtpClient())
    {
        return smtpClient.SendMailAysnc(new MailMessage());
    }
}
Run Code Online (Sandbox Code Playgroud)

或者后者实际上不是异步运行?

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

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

async一直等待异步

我是c#异步等待机制的新手.我一直在阅读一些关于异步的文章(http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html).我在下面有一个例子,如果第Initialize一种方法会导致死锁,为什么还能告诉我?先感谢您.

public class Test {

    public  async  Task DoSomeWorkAsync() {
      await DoSomeWork1Async(); 
    }

    // This method is mixed with Wait and async await, will this cause lead lock?
    public void Initialize() {
      Task.Run(() => DoSomeWorkAsync()).Wait();
    }

    // This method is following async all the way
    public async Task InitializeAsync()  {
      await DoSomeWorkAsync();
    }

}

// Update: Here is the context where two Initialize methods are called
public class TestForm : Form {
  // Load Form UI …
Run Code Online (Sandbox Code Playgroud)

.net c# wait task-parallel-library async-await

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

什么是BatchBlock的相反块

鉴于:

电子邮件ID列表

我在做什么:

使用BatchBlock组ID并为每个块调用Transformblock,简化的transformblock如下所示:

var readBatch = new TransformBlock<List<int>, IEnumerable<Email>>(idList =>
{
    List<Email> mails = new List<Email>();
    foreach(var id in idList)
    {
        mails.Add(new Email(id));
    }
    return mails;
});
Run Code Online (Sandbox Code Playgroud)

现在我的下一个TransformBlock定义如下

TransformBlock<Email,EMail> filterStep;
Run Code Online (Sandbox Code Playgroud)

我搜索的内容:所以我需要一个块,它允许我将一个集合作为源并返回N-Elements作为结果.因此,在这种情况下,一个块接收一个IEnumerable<Email>Email在枚举中返回foreach条目.

所以我搜索的是BatchBlock的反面但我找不到它.我忽略了什么吗?

.net c# task-parallel-library tpl-dataflow

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

SynchronizationContext - 奇怪的行为

public static void Init()
{
    //var task = GetSource1();
    //var task = GetSource2();
    //var task = GetSource3();
    var task = MyClient();
    MessageBox.Show(task.Result);
}

private static async Task<string> GetSource1()
{
    var sourceTask = WebClient();
    sourceTask.ConfigureAwait(false);
    return await sourceTask;
}

private static async Task<string> GetSource2()
{
    var sourceTask = MyClient();
    sourceTask.ConfigureAwait(true);
    return await sourceTask;
}

private static async Task<string> GetSource3()
{
    var sourceTask = MyClient();
    sourceTask.ConfigureAwait(false);
    return await sourceTask;
}

private static async Task<string> WebClient()
{
    return await new WebClient().DownloadStringTaskAsync("http://4pda.ru").ConfigureAwait(false);
}

private …
Run Code Online (Sandbox Code Playgroud)

.net c# synchronizationcontext task-parallel-library async-await

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

从任务内部取消任务

我正在使用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)

可以取消这样的任务吗?或者我做错了什么?

.net c# task-parallel-library

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