小编nel*_*eus的帖子

在请求取消之前永远不会结束的任务

我需要一个永远不会结束的任务,直到请求取消.目前最简单的方法是:

var cancellation = new CancellationTokenSource();

var task = Task.Factory.StartNew(async () =>
{
    while (true)
    {
        await Task.Delay(10000, cancellation.Token);
    }
}, cancellation.Token).Unwrap();
Run Code Online (Sandbox Code Playgroud)

我不喜欢的是对Task.Delay方法的调用,因为它需要有限的等待时间间隔.

有更优雅的解决方案吗?

.net asynchronous task-parallel-library

8
推荐指数
2
解决办法
1105
查看次数

ConfigureAwait(false)导致错误而不是死锁的情况

假设我编写了一个依赖于async方法的库:

namespace MyLibrary1
{
    public class ClassFromMyLibrary1
    {
        public async Task<string> MethodFromMyLibrary1(string key, Func<string, Task<string>> actionToProcessNewValue)
        {
            var remoteValue = await GetValueByKey(key).ConfigureAwait(false);

            //do some transformations of the value
            var newValue = string.Format("Remote-{0}", remoteValue);

            var processedValue = await actionToProcessNewValue(newValue).ConfigureAwait(false);

            return string.Format("Processed-{0}", processedValue);
        }

        private async Task<string> GetValueByKey(string key)
        {
            //simulate time-consuming operation
            await Task.Delay(500).ConfigureAwait(false);

            return string.Format("ValueFromRemoteLocationBy{0}", key);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我遵循了在我的图书馆里到处使用ConfigureAwait(false)(就像在这篇文章中)的建议.然后我从我的测试应用程序以同步方式使用它并获得失败:

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary> …
Run Code Online (Sandbox Code Playgroud)

.net c# synchronizationcontext async-await

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

C#扩展方法重载导致"缺少程序集引用"错误

有一个相应的VS开发票https://connect.microsoft.com/VisualStudio/feedback/details/817276/error-cs0012-the-type-is-defined-in-an-assembly-that-is-not-referenced -issued换的延伸法-即-是-未使用

我有2种扩展方法:

public static class ExtensionMethods
{
    public static string GetClientIpAddress(this HttpRequestBase request)
    {
        // ...
    }

    public static string GetClientIpAddress(this HttpRequestMessage request)
    {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

HttpRequestMessage位于System.Net.Http组件中并且HttpRequestBase位于System.Web(即在不同的组件中).该课程ExtensionMethods位于ProjectA中.

这个项目汇编得很好,没有任何问题.

然后我使用GetClientIpAddress(this HttpRequestBase request)另一个项目中的第一个方法(比如说ProjectB),如下所示:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    base.OnActionExecuting(filterContext);
    var sessionContext = DependencyResolver.Current.GetService<ISessionContext>();

    // Call to GetClientIpAddress
    sessionContext.ClientIpAddress =
        filterContext.HttpContext.Request.GetClientIpAddress();
}
Run Code Online (Sandbox Code Playgroud)

ProjectB已经引用了System.Web,但是当我尝试编译它时,它会导致编译器错误:

类型' System.Net.Http.HttpRequestMessage'在未引用的程序集中定义.您必须添加对程序集' System.Net.Http, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a …

c# extension-methods c#-5.0

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

为什么Task.WhenAll抛出TaskCanceledException和Task.WhenAny不在同一个测试用例中

我运行这段代码:

var cancellation = new CancellationTokenSource();
var cancelledTask1 = .....;//starting new long-running task that accepts cancellation.Token
var cancelledTask2 = .....;//starting new long-running task that accepts cancellation.Token

//then I request cancellation
cancellation.Cancel();
//some task gets cancelled before code below executes
try
{
    //wait for completion (some task is already in cancelled state)
    await Task.WhenAll(cancelledTask1, cancelledTask2);
}
catch (OperationCanceledException e)
{
    Logger.Debug("await WhenAll", e);
}
Run Code Online (Sandbox Code Playgroud)

我明白了

await WhenAll System.Threading.Tasks.TaskCanceledException: A task was canceled.
Run Code Online (Sandbox Code Playgroud)

我认为它很少,因为某些任务已经处于取消状态.为什么Task.WhenAll方法会破坏正常流程并在取消子任务时抛出异常?什么是受益于这种行为?

然后,我尝试了这个方法Task.WhenAny:

var cancellation = …
Run Code Online (Sandbox Code Playgroud)

.net asynchronous async-await

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

当明确定义枚举值时,WCF客户端失败

我的问题与类似,但有一个有趣的区别。我已经明确定义了所有值,但仍然无法正常工作。如果可能,我也尽量避免使用合同属性。

所以这一切看起来像什么。我定义了一个具有枚举类型的属性的合同。枚举是

public enum ErrorCodes
{
    GeneralError = 1,
    ValidationError = 2,
    AuthenticationError = 3
}
Run Code Online (Sandbox Code Playgroud)

然后客户端因错误而失败:

System.ServiceModel.CommunicationException: An error occurred while receiving the HTTP response to http://localhost/MyTestAppService/SomeService.svc/soap. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details. ---> System.Net.WebException: The underlying connection was closed: An …
Run Code Online (Sandbox Code Playgroud)

.net wcf enums datacontract

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