-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
106 lines (94 loc) · 3.19 KB
/
Copy pathProgram.cs
File metadata and controls
106 lines (94 loc) · 3.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Reflection.Metadata;
using System.Threading.Tasks;
namespace AsyncProcessing
{
class Rekord
{
public int ID { get; set; }
public int wartosc { get; set; }
public string operacja { get; set; }
public int proby { get; set; } = 0;
}
class SharedState
{
public int Value { get; set; }
public int pominiete { get; set; } = 0;
}
class Program()
{
static async Task Main()
{
var stan = new SharedState() { Value = 0 };
var kolejka = new ConcurrentQueue<Rekord>();
Console.WriteLine("podaj wielkosc zbioru");
if(!int.TryParse(Console.ReadLine(), out int wielkoscZbioru) || wielkoscZbioru <=0) {
Console.WriteLine("zla liczba");
return;
}
var rand = new Random();
string[] operacje = { "dodawanie", "odejmowanie" };
for(int i = 0; i < wielkoscZbioru; i++)
{
kolejka.Enqueue(new Rekord
{
ID = i,
wartosc = rand.Next(0, 10),
operacja = operacje[rand.Next(0, 2)]
});
}
Task t1 = operuj(kolejka, stan);
Task t2 = operuj(kolejka, stan);
Task t3 = operuj(kolejka, stan);
Task.WaitAll(t1,t2,t3);
Console.WriteLine($"koniec, stan: {stan.Value}");
Console.WriteLine($"pominiete: {stan.pominiete}");
}
private static readonly object lockKey = new object();
static async Task operuj(ConcurrentQueue<Rekord> kolejka, SharedState stanWspolny)
{
var rand = new Random();
while(kolejka.TryDequeue(out Rekord rekord))
{
try
{
if(rand.Next(0, 100) <= 20)
{
throw new Exception("blad");
}
if(rand.Next(0,100) <= 10)
{
stanWspolny.pominiete++;
continue;
}
lock (lockKey)
{
if (rekord.operacja == "dodawanie")
{
stanWspolny.Value += rekord.wartosc;
}
else if (rekord.operacja == "odejmowanie")
{
stanWspolny.Value -= rekord.wartosc;
}
}
Console.WriteLine($"id: {rekord.ID}, wartosc: {rekord.wartosc}, operacja: {rekord.operacja}, stan po operacji: {stanWspolny.Value}");
}
catch (Exception ex)
{
rekord.proby++;
if(rekord.proby<3)
{
kolejka.Enqueue(rekord);
}
else
{
stanWspolny.pominiete++;
}
}
}
}
}
}