小编Dou*_* M.的帖子

Parallel.For和For产生不同的结果

如果我运行此测试:

 var r = new Random();
 var ints = new int[13];
 Parallel.For(0, 2000000, i => {            
     var result = r.Next(1, 7) + r.Next(1, 7);
     ints[result] += 1;
 });
Run Code Online (Sandbox Code Playgroud)

我得到以下结果:

2: 92,14445
3: 0,41765
4: 0,62245
5: 0,82525
6: 1,04035
7: 1,25215
8: 1,0531
9: 0,8341
10: 0,6334
11: 0,4192
12: 0,2109
Run Code Online (Sandbox Code Playgroud)

当我使用常规For:

for (int i = 0; i < 2000000; i++) {
    var result = r.Next(1, 7) + r.Next(1, 7);
    ints[result] += 1;
}
Run Code Online (Sandbox Code Playgroud)

输出是:

2: 2,7797
3: 5,58645
4: …
Run Code Online (Sandbox Code Playgroud)

c# parallel-processing multithreading c#-4.0

13
推荐指数
2
解决办法
627
查看次数

使用ContinueWith或Async-Await时的不同行为

当我在HttpClient调用中使用async-await方法(如下例所示)时,此代码会导致死锁.用a替换async-await方法t.ContinueWith,它可以正常工作.为什么?

public class MyFilter: ActionFilterAttribute {
    public override void OnActionExecuting(ActionExecutingContext filterContext) {
         var user = _authService.GetUserAsync(username).Result;
    }
}

public class AuthService: IAuthService {
    public async Task<User> GetUserAsync (string username) {           
        var jsonUsr = await _httpClientWrp.GetStringAsync(url).ConfigureAwait(false);
        return await JsonConvert.DeserializeObjectAsync<User>(jsonUsr);
    }
}
Run Code Online (Sandbox Code Playgroud)

这有效:

public class HttpClientWrapper : IHttpClient {
    public Task<string> GetStringAsync(string url) {           
        return _client.GetStringAsync(url).ContinueWith(t => {
                _log.InfoFormat("Response: {0}", url);                    
                return t.Result;
        });
}
Run Code Online (Sandbox Code Playgroud)

这段代码会死锁:

public class HttpClientWrapper : IHttpClient {
    public async Task<string> GetStringAsync(string url) { …
Run Code Online (Sandbox Code Playgroud)

.net c# asp.net-mvc multithreading async-await

7
推荐指数
2
解决办法
6112
查看次数

LINQ:显示空列表的结果

我在C#中创建了两个实体(简化):

class Log {  
    entries = new List<Entry>();

    DateTime Date { get; set; }  
    IList<Entry> entries { get; set; }  
}  

class Entry {  
    DateTime ClockIn { get; set; }  
    DateTime ClockOut { get; set; }  
}  
Run Code Online (Sandbox Code Playgroud)

我使用以下代码初始化对象:

Log log1 = new Log() {
    Date = new DateTime(2010, 1, 1),                
};
log1.Entries.Add(new Entry() {
    ClockIn = new DateTime(0001, 1, 1, 9, 0, 0),
    ClockOut = new DateTime(0001, 1, 1, 12, 0, 0)
});

Log log2 = new Log()
{
    Date …
Run Code Online (Sandbox Code Playgroud)

c# linq

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