I have a program in which I want to Simulate a queue. To speed things up (lots of different parameters) I thought that I could use a parallel loop, however the queue object (or at least the objects within that object) are still shared while they are all created within either the MGcC function or the queue object. Is there something I forgot about parallel functions?
The object which gives the trouble is the queue.MyHeap.
(Also if more information is needed please ask as I have left out a lot to make it more readably as you might see in the queue object).
Parallel.ForEach(a, (numbers) =>
{
MGcC(a);
});
static public Tuple<Customer[,], List<Interval>[]> MGcC(int a)
{
Queue queue = new Queue(a);
return queue.Simulate(writeFile);
}
public class Queue
{
Func<object, double> arrivalFunction;
Func<object, double> servingFunction;
double lambda;
double v;
object serviceObject;
int minServers;
bool decision;
int idleServers;
int activeServers;
int amountInOrbit;
protected minHeap myHeap;
public Queue(double lambda, double v, object serviceObject, int servers, Func<object, double> arrivalFunction, Func<object, double> servingFunction, bool decision = false)
{
this.arrivalFunction = arrivalFunction;
this.servingFunction = servingFunction;
this.lambda = lambda;
this.v = v;
this.serviceObject = serviceObject;
this.minServers = servers;
this.decision = decision;
idleServers = servers;
activeServers = 0;
amountInOrbit = 0;
myHeap = new minHeap();
}
public class minHeap
{
static protected Action[] heap;
static public int counter;
public minHeap()
{
counter = -1;
heap = new Action[1000000];
}
public Action Pop()
{
if (counter < 0)
{
Console.WriteLine("empty");
return new Action(0, 0, new Customer());
}
Action returnValue = heap[0];
heap[0] = heap[counter];
counter--;
heapify(0);
return (returnValue);
}
public void Push(Action a)
{
counter++;
heap[counter] = new Action(double.PositiveInfinity, 0, new Customer());
InsertKey(counter, a);
}
static void InsertKey(int i, Action a)
{
if (heap[i].TimeOfExecution < a.TimeOfExecution)
Console.WriteLine("should not have happened");
heap[i] = a;
while (i > 0 && heap[Parent(i)].TimeOfExecution > heap[i].TimeOfExecution)
{
Action temp = heap[i];
heap[i] = heap[Parent(i)];
heap[Parent(i)] = temp;
i = Parent(i);
}
}
All the fields on your minHeap type are static. So yes: they're shared - that's what static means. You probably want to make them non-static.
Possibly you used static when you meant readonly?
Related
I have a list and in the list there are multiple entries. If the list contains an entry that is duplicated then I want to only keep one of the duplicates.
I've tried many things, the list.Distinct().ToList() and this does not remove the duplicate entry, I do not want to override the classes Equals method, so is there a way outside of that.
I've also done this method which seems to again, not remove the duplicate entry as it does not consider object a == object b.
private void removeDupes(List<Bookings> list)
{
int duplicates = 0;
int previousIndex = 0;
for (int i = 0; i < list.Count; i++)
{
bool duplicateFound = false;
for (int x = 0; x < i; x++)
{
if (list[i] == list[x])
{
duplicateFound = true;
duplicates++;
break;
}
}
if (duplicateFound == false)
{
list[previousIndex] = list[i];
previousIndex++;
}
}
}
There is another overload of the Distinct LINQ extension method that also takes an IEqualityComparer as an argument (see this link). So you'd need to create a class that implements IEqualityComparer<Bookings> and supply an instance of it to the Distinct-method. This way, you do not need to override the Equals method of the type.
The rules on whether two objects are equal to one another are implemented in the EqualityComparer.
As an alternative, you can use a HashSet and supply the EqualityComparer in the constructor.
A possible solution for your problem in order of Markus answer might look like this:
public class Booking
{
public Booking(int id, float amount)
{
BookingId = id;
BookingAmount = amount;
}
public int BookingId { get; }
public float BookingAmount { get; }
}
public class BookingComparer : IEqualityComparer<Booking>
{
public bool Equals(Booking x, Booking y)
{
return (x.BookingAmount == y.BookingAmount) && (x.BookingId == y.BookingId);
}
public int GetHashCode(Booking obj)
{
return obj.BookingId.GetHashCode()*17 + obj.BookingAmount.GetHashCode()*17;
}
}
internal class Program
{
private static void Main(string[] args)
{
var booking1 = new Booking(1, 12);
var booking2 = new Booking(1, 12);
var bookings = new List<Booking>();
bookings.Add(booking1);
bookings.Add(booking2);
var result = bookings.Distinct(new BookingComparer()).ToList();
}
}
I need help. I'm making a programm and i have a problem.
I have a constructor with delegate already:
public delegate bool delIsDone(int curState, int needState);
public Progress(delIsDone doneFunction) { ... }
I need to pass it without creating it outside of creation:
public bool check() { return true }
Progress p = new Progress(check);
I need to do something like this:
Progress p = new ProgressChecker(bool check(int currentProgress, int needProgress) {
return currentProgress < needProgress;
});
Where ProgressChecker is a class that have method that check progress.
In loop i execute this function to get result. If function return "true" it's mean that "Achievement geted" and i need to hold it.
Thx for help
In the constructor you can pass in a function like so:
ProgressChecker(Func<int,int,bool> checker)
That means you can pass a function into the constructor for ProgressChecker
public bool checker (int a, int b)
{
return a < b;
}
var t = new ProgressChecker(checker);
EDIT:
If you want to use the delegate, then in the ProgressChecker class, the constructor must take in that delegate type:
private delIsDone delIsDone;
public ProgressChecker(delIsDone delIsDone)
{
this.delIsDone = delIsDone;
}
You can the pass a delegate instance like so:
public class Program
{
public delegate bool delIsDone(int curState, int needState);
public static bool checkNumbers(int a, int b)
{
return a < b;
}
public static void Main(string[] args)
{
var t = new ProgressChecker(new delIsDone(checkNumbers));
// OR var t = new ProgressChecker(new delIsDone((a, b) => { return a < b; }));
}
}
You can also create Expression Trees, it is my snippet for it (it can be easly converted to your example)
//easy way
Expression<Action<int>> printExpr = (arg) => Console.WriteLine(arg);
printExpr.Compile()(10);
//hard way
ParameterExpression param = Expression.Parameter(typeof(int), "arg");
MethodCallExpression methodCall = Expression.Call
(
typeof(Console).GetMethod("WriteLine", new[]
{
typeof(int)
}
),
param
);
Expression.Lambda<Action<int>>(methodCall, param).Compile()(10); //execution
More information ca be gathered at Generating Dynamic Methods with Expression Trees
I have something like this. How can i return value form anonymous method?
returnRate = d;. For example let i have some class which get's messages from server. I want to process those messages in classes Cars and Bicycles is that clearly now?
namespace ConsoleApplication9
{
class Program
{
static void Main(string[] args)
{
Cars c = new Cars();
Bicycles b = new Bicycles();
}
}
public class Cars
{
public Cars()
{
GetData G1 = new GetData();
Dictionary<string, string> D1 = new Dictionary<string, string>();
G1.ProcessCars(ref D1);
}
}
public class Bicycles
{
public Bicycles()
{
GetData G2 = new GetData();
Dictionary<string, string> D2 = new Dictionary<string, string>();
G2.ProcessBicycles(ref D2);
}
}
public class Singleton
{
private static Singleton instance;
public Dictionary<string, Action<MessageEventArgs>> Handle;
private Singleton()
{
Handle = new Dictionary<string, Action<MessageEventArgs>>();
}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
public class GetData
{
private Client socket;
public GetData()
{
socket = new Client("http://echo.jsontest.com/bicycles/10");
socket.Message += Message;
}
public void ProcessBicycles(ref Dictionary<string, string> returnRate)
{
Singleton.Instance.Handle.Add("bicycles", (m) =>
{
Dictionary<string, string> d = m.Message.Json.GetFirstArgAs<Dictionary<string, string>>() as Dictionary<string, string>;
//returnRate = d;
});
}
public void ProcessCars(ref Dictionary<string, string> returnRate)
{
Singleton.Instance.Handle.Add("cars", (m) =>
{
Dictionary<string, string> d = m.Message.Json.GetFirstArgAs<Dictionary<string, string>>() as Dictionary<string, string>;
//returnRate = d;
});
}
private void Message(object sender, MessageEventArgs e)
{
if (Singleton.Instance.Handle.ContainsKey(e.Message.Event))
{
Singleton.Instance.Handle[e.Message.Event](e);
}
}
}
}
You'll have to pass in the Action yourself, rather than creating it with a ref parameter. So your Add method simply becomes:
public void Add(Action<string> action) {
Handle.Add("1", action);
}
You can call it like this:
Add(m => ReturnRate = m);
This is a kind of Callback function, which can be used for a kind of asynchronous programming. However, it might be worth your time to read about async and await. If you could give us more information about what your scenario exactly is, we might be able to give you more hints.
If you have to use a ref parameter (for some strange reason), I think you're out of luck...
You should use Func<string,string> instead Action
Action<string> means void function(string s)
Func<string,string> means string function(string s)
However it depends on usage you want to achieve.
This is because the used variables that are used in the the anonymous method body but are outside of it, will be public fields in the generated class made by the compiler. But you can introduce a local variable to make it compilable:
public void Add(ref string rate)
{
string r = rate;
Handle.Add("1", (m) =>
{
Console.WriteLine(m);
r = m;
});
rate = r;
}
And the compiler will generate this in the background:
public void Add(ref string rate)
{
<>c__DisplayClass1 CS$<>8__locals2 = new <>c__DisplayClass1();
CS$<>8__locals2.r = rate;
this.Handle.Add("1", new Action<string>(CS$<>8__locals2.<Add>b__0));
rate = CS$<>8__locals2.r;
}
[CompilerGenerated]
private sealed class <>c__DisplayClass1
{
public string r;
public void <Add>b__0(string m)
{
Console.WriteLine(m);
this.r = m;
}
}
Note: Though this can be compiled, it will not work as you expect, because calling the outer Add will not execute the delegate added by Handle.Add. To return the m from the inner delegate you must use a Func instead.
You should use Func<string,string> (delegate Func<in T,out TResult>) which is equivalent to some function that takes in string and returns string
for eg:-
private string MyFunction(string inputstring){}
Whereas Action<string> (delegate Action<in T>) corresponds to a function which only takes input and returns nothing
private void MyFunction(string inputstring){}
You can modify your code to something like
private Dictionary<string, Func<string,string>> Handle;
private string ReturnRate;
public data()
{
Handle = new Dictionary<string, Func<string,string>>();
Add(ref ReturnRate);
Handle["1"]("MyValue");
Console.WriteLine(ReturnRate);
}
public void Add(ref string rate)
{
string somevalue=rate;
Handle.Add("1", (m) =>
{
Console.WriteLine(m);
somevalue= m;
return m;
});
}
How to create dynamic incrementing variable using "for" loop in C#? like this:
track_1, track_2, track_3, track_4. so on.
You can't create dynamically-named variables. All you can do - it to create some collection or array, and operate with it.
I think the best class for you is generic List<>:
List<String> listWithDynamic = new List<String>();
for (int i = 1; i < limit; i +=1)
{
listWithDynamic.Add(string.Format("track_{0}", i));
...
}
Assuming you want strings:
for (int i = 1; i < limit; i +=1)
{
string track = string.Format("track_{0}", i);
...
}
But when you already have variables called track_1, track_2, track_3, track_4 you will need an array or List:
var tracks = new TrackType[] { track_1, track_2, track_3, track_4 } ;
for (int i = 0; i < tracks.length; i++)
{
var track = tracks[i]; // tracks[0] == track_1
...
}
Obvious Solution
for (var i = 0; i < 10; i++)
{
var track = string.Format("track_{0}", i);
}
Linq-Based Solution
foreach (var track in Enumerable.Range(0, 100).Select(x => string.Format("track_{0}", x)))
{
}
Operator-Based Solution This is somewhat hacky, but fun none-the-less.
for (var i = new Frob(0, "track_{0}"); i < 100; i++)
{
Console.WriteLine(i.ValueDescription);
}
struct Frob
{
public int Value { get; private set; }
public string ValueDescription { get; private set; }
private string _format;
public Frob(int value, string format)
: this()
{
Value = value;
ValueDescription = string.Format(format, value);
_format = format;
}
public static Frob operator ++(Frob value)
{
return new Frob(value.Value + 1, value._format);
}
public static Frob operator --(Frob value)
{
return new Frob(value.Value - 1, value._format);
}
public static implicit operator int(Frob value)
{
return value.Value;
}
public static implicit operator string(Frob value)
{
return value.ValueDescription;
}
public override bool Equals(object obj)
{
if (obj is Frob)
{
return ((Frob)obj).Value == Value;
}
else if (obj is string)
{
return ((string)obj) == ValueDescription;
}
else if (obj is int)
{
return ((int)obj) == Value;
}
else
{
return base.Equals(obj);
}
}
public override int GetHashCode()
{
return Value;
}
public override string ToString()
{
return ValueDescription;
}
}
don't know if I get your question, but I will try:
for(var i = 1; i < yourExclusiveUpperbound; i++)
{
var track = String.Format("$track_{0}", i);
// use track
}
or with some LINQ-Magic:
foreach(var track in Enumerate.Range(1, count)
.Select(i => String.Format("$track_{0}", i)))
{
// use track
}
Do as follow:
for (int i = 0; i < lenght; i ++)
{
any work do in loop
}
No, we can't create dynamically named variables in a loop. But, there are other elegant ways to address the problem instead of creating dynamically named variables.
One could be, create an array or list before the loop and store values in array / list items in the loop. You can access the array / list later anywhere in your code. If you know which variable you want to use (track_1, track_2, ...), you can simply access it from the array / list (tracks[1], tracks[2], ...).
List<String> tracks = new List<String>();
for (int i = 1; i < limit; i++)
{
Track track = new Track();
tracks.Add(track);
...
}
Mostly it comes handy that C# delegates already store the object together with the member function. But is there a way, to store -- and pass as parameters -- only the member function itself, just as the good old pointer-to-member-function in C++?
In case the description is less than clear, I give a self-contained example. And, yes, in the example the insistence to pass around member functions is totally pointless, but I have more serious uses for this.
class Foo {
public int i { get; set; }
/* Can this be done?
public static int Apply (Foo obj, ???? method, int j) {
return obj.method (j);
}
*/
public static int ApplyHack (Foo obj, Func<int, int> method, int j) {
return (int) method.Method.Invoke (obj, new object [] { j });
}
public static readonly Foo _ = new Foo (); // dummy object for ApplyHack
public int Multiply (int j) {
return i * j;
}
public int Add (int j) {
return i + j;
}
}
class Program {
static void Main (string [] args) {
var foo = new Foo { i = 7 };
Console.Write ("{0}\n", Foo.ApplyHack (foo, Foo._.Multiply, 5));
Console.Write ("{0}\n", Foo.ApplyHack (foo, Foo._.Add, 5));
Console.ReadKey ();
}
}
You see, the only workaround I've found is rather ugly and probably slow.
What you want is something called an open instance delegate. I've written about them on my blog
Basically, you can create a delegate to an instance method without tying it to a particular instance, and specify the instance to use it on when you call it:
class Foo {
public int i { get; set; }
public int Multiply (int j) {
return i * j;
}
public int Add (int j) {
return i + j;
}
}
class Program {
static void Main (string [] args) {
Func<Foo, int, int> multiply = (Func<Foo, int, int>)Delegate.CreateDelegate(typeof(Func<Foo, int, int>), null, typeof(Foo).GetMethod("Multiply");
Func<Foo, int, int> add = (Func<Foo, int, int>)Delegate.CreateDelegate(typeof(Func<Foo, int, int>), null, typeof(Foo).GetMethod("Add");
var foo1 = new Foo { i = 7 };
var foo2 = new Foo { i = 8 };
Console.Write ("{0}\n", multiply(foo1, 5));
Console.Write ("{0}\n", add(foo1, 5));
Console.Write ("{0}\n", multiply(foo2, 5));
Console.Write ("{0}\n", add(foo2, 5));
Console.ReadKey ();
}
}
Taking your existing code:
public static int ApplyHack (Foo obj, Func<int, int> method, int j) {
return (int) method.Method.Invoke (obj, new object [] { j });
}
You could do something like this:
public static int ApplyHack (Foo obj, Func<int, int> method, int j) {
var func = (Func<int,int>)Delegate.CreateDelegate(typeof(Func<int,int>), obj, method.Method);
return func(j);
}
This will create a new delegate around the method and the new object. To take your first example:
public static int Apply (Foo obj, ???? method, int j) {
return obj.method (j);
}
The type you are looking for is System.Reflection.MethodInfo and it would look like this:
public static int Apply (Foo obj, MethodInfo method, int j) {
var func = (Func<int,int>)Delegate.CreateDelegate(typeof(Func<int,int>), obj, method);
return func(i);
}
Note that while you are allocating delegates for each invocation, I believe this will still be faster than using reflection, since you do not have to box function input/output, nor store it in object[] arrays.
Assuming you're using C# 2.0 or above, and have access to anonymous delegates, you can do it very simply by wrapping the function in an anonymous delegate at the point of storage:
class Foo
{
public Foo(int v)
{
this.v = v;
}
int v;
public int Multiply(int x)
{
return v * x;
}
public int Add(int x)
{
return v+x;
}
delegate int NewFunctionPointer(Foo, int);
delegate int OldDelegateStyle(int);
static void Example()
{
Foo f = new Foo(2);
Foo f2 = new Foo(3);
// instead of this, which binds an instance
OldDelegateStyle oldMul = f.Multiply;
// You have to use this
NewFunctionPointer mul = delegate(Foo f, int x) { return f.Multiply(x); }
NewFunctionPointer add = delegate(Foo f, int x) { return f.Add(x); }
// But can now do this
mul(f, 4); // = 8
add(f2, 1); // = 3
}
}
If you're okay with passing the this reference as a parameter, why not just use static methods?
class Foo {
public int i;
public static int ApplyHack(Foo foo, Func<Foo, int, int> method, int j) {
return method(foo, j);
}
public static int Multiply(Foo foo, int j) {
return foo.i * j;
}
}
Console.Write("{0}\n", Foo.ApplyHack(foo, Foo.Multiply, 5));
This mainly affects how you construct the Foo object, without changing how you use it. It also doesn't prevent you from having a non-static int Multiply(int) method.
You could retrieve and reuse the MethodInfo for the method or just use the name and extract the method at runtime.
public static int ApplyHack (Foo obj, string methodName, int j)
{
var method = typeof(Foo).GetMethod(methodName);
return (int) method.Invoke (obj, new object [] { j });
}
I'd be very careful that this was actually necessary as it seems like a code smell to me.
You can do it that way
class Foo
{
public int i { get; set; }
public static int Apply(Foo obj, Func<int, int, int> method, int j)
{
return method(j, obj.i);
}
public static int Multiply(int j, int i)
{
return i * j;
}
public static int Add(int j, int i)
{
return i + j;
}
}
static void Main(string[] args)
{
var foo = new Foo { i = 7 };
Console.Write("{0}\n", Foo.Apply(foo, Foo.Multiply, 5));
Console.Write("{0}\n", Foo.Apply(foo, Foo.Add, 5));
Console.ReadKey();
}
I think you can do this easily with this if I understand correctly:
public static int Apply(Func<int, int> method, int j)
{
return (int)method.Method.Invoke(method.Target, new object[] { j });
}
and call it like this:
Console.Write("{0}\n", Foo.Apply(foo.Multiply, 5));