|
jojoba2011 wrote: thanks but i get error. Can u give me a small example! If you'd get an error, it'd be more helpfull to solve that, than blindly trying examples.
I'm guessing that it's due to the fact that you only have the body of a method in there; just like in Visual Studio, the code needs to be located in a class. Try the example below in a console-application.
using System;
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using Microsoft.CSharp;
class Program
{
static void Main(string[] args)
{
string sources = @"
using System;
public static class ExampleClass
{
public static void ExampleMethod()
{
Console.WriteLine(""Hello World!"");
}
}";
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
string Output = "Out.dll";
CompilerParameters parameters = new CompilerParameters()
{
GenerateExecutable = false,
OutputAssembly = Output
};
CompilerResults results = codeProvider.CompileAssemblyFromSource(
parameters, sources);
if (results.Errors.Count > 0)
{
foreach (CompilerError CompErr in results.Errors)
{
Console.WriteLine(
"Line number " + CompErr.Line +
", Error Number: " + CompErr.ErrorNumber +
", '" + CompErr.ErrorText + ";");
}
}
else
{
Assembly myAssembly = Assembly.Load(File.ReadAllBytes("Out.dll"));
Type myType = myAssembly.GetType("ExampleClass");
MethodInfo mi = myType.GetMethod("ExampleMethod");
mi.Invoke(null, null);
}
Console.WriteLine("Hit any user to continue");
Console.ReadKey();
}
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
vote => up.
That's a very useful, and complete, example, thanks !
"What Turing gave us for the first time (and without Turing you just couldn't do any of this) is he gave us a way of thinking about and taking seriously and thinking in a disciplined way about phenomena that have, as I like to say, trillions of moving parts.
Until the late 20th century, nobody knew how to take seriously a machine with a trillion moving parts. It's just mind-boggling." Daniel C. Dennett
|
|
|
|
|
thanks in advanced!
My question is this :
Is it possible to excute code without creating any class ....?
string sources = @"
using System;
public static class ExampleClass
{
public static void ExampleMethod()
{
Console.WriteLine(""Hello World!"");
}
}";
and one more :
How to use the textBox1.Text and other controls values?
|
|
|
|
|
jojoba2011 wrote: Is it possible to excute code without creating any class ....? No. Then again, it wouldn't be much work to wrap it automatically in a class; it's just text after all. Also keep in mind that this class will not be "unloaded".
jojoba2011 wrote: How to use the textBox1.Text and other controls values? You see that using? The code one compiles needs to have a reference to your project. That means including a "using" directive in the source code, as well as adding a reference[^] to the compilerparameters.
You could save a lot of pain by rewriting that part of the code to use variables/parameters, and not directly the UI-elements of your project.
--edit;
Alternatively, if you'd install Mono, there'd be the Eval[^] method.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
modified 16-Nov-13 16:18pm.
|
|
|
|
|
When I'm debugging, I do the following
string st = something
if (textBox1.Text == "Jon" && chkText.Checked)
MessageBox.Show(st + " (if)");
else
MessageBox.Show(st + " (else)");"
|
|
|
|
|
|
i got the solution :
http://stackoverflow.com/questions/14485226/convert-string-to-executable-c-sharp-code-in-code-behind
Solved !
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
private System.Windows.Forms.TextBox txtf;
private System.Windows.Forms.TextBox txts;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox txt;
//public Form1()
//{
// InitializeComponent();
//}
public Form1()
{
this.txtf = new System.Windows.Forms.TextBox();
this.txts = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.txt = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// txtf
//
this.txtf.Location = new System.Drawing.Point(81, 125);
this.txtf.Name = "txtf";
this.txtf.Size = new System.Drawing.Size(100, 20);
this.txtf.TabIndex = 0;
//
// txts
//
this.txts.Location = new System.Drawing.Point(81, 161);
this.txts.Name = "txts";
this.txts.Size = new System.Drawing.Size(100, 20);
this.txts.TabIndex = 0;
//
// button1
//
this.button1.Location = new System.Drawing.Point(81, 196);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 1;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// txt
//
this.txt.Location = new System.Drawing.Point(12, 12);
this.txt.Multiline = true;
this.txt.Name = "txt";
this.txt.Size = new System.Drawing.Size(260, 107);
this.txt.TabIndex = 0;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 261);
this.Controls.Add(this.button1);
this.Controls.Add(this.txts);
this.Controls.Add(this.txt);
this.Controls.Add(this.txtf);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private static string CreateExecuteMethodTemplate(string content)
{
var builder = new StringBuilder();
builder.Append("using System;");
builder.Append("\r\nnamespace Lab");
builder.Append("\r\n{");
builder.Append("\r\npublic sealed class Cal");
builder.Append("\r\n{");
builder.Append("\r\npublic static object Execute()");
builder.Append("\r\n{");
//builder.AppendFormat("\r\nreturn {0};", content);
builder.AppendFormat("\r\n {0} ", content);
builder.Append("\r\n}");
builder.Append("\r\n}");
builder.Append("\r\n}");
return builder.ToString();
}
private static object Execute(string content)
{
var codeProvider = new CSharpCodeProvider();
var compilerParameters = new CompilerParameters
{
GenerateExecutable = false,
GenerateInMemory = true
};
compilerParameters.ReferencedAssemblies.Add("system.dll");
string sourceCode = CreateExecuteMethodTemplate(content);
CompilerResults compilerResults = codeProvider.CompileAssemblyFromSource(compilerParameters, sourceCode);
Assembly assembly = compilerResults.CompiledAssembly;
Type type = assembly.GetType("Lab.Cal");
MethodInfo methodInfo = type.GetMethod("Execute");
return methodInfo.Invoke(null, null);
}
private void button1_Click(object sender, EventArgs e)
{
string Matn = txt.Text;
Matn = Matn.Replace(txtf.Name, txtf.Text);
Matn = Matn.Replace(txts.Name, txts.Text);
var result = new object();
result = Execute(Matn);
MessageBox.Show(result.ToString());
//result =Execute("DateTime.Now");
//result = Execute("if(\"ali\"==\"ali\")return \"true\"; else return \"false\";");
}
}
}
|
|
|
|
|
I've been trying to run a simple block of code from C sharp in a powershell run space.
I went to run that command in the powershell example project on my workstation and it did not work, but that demo application will run on the server that has scom installed.
Is there a management pack (like with Exchange) that I need to install on my workstation to get access to the dlls and commands that I have through powershell when on the server locally. Any ideas?
Import-Module –Name OperationsManager
New-SCOMManagementGroupConnection -ComputerName "serverName"
get-scomgroup
foreach ($group in get-scomgroup)
{
Write-Host $group
}
How to run PowerShell scripts from C#[^]
|
|
|
|
|
Explained here[^]
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Thank you Eddy.
I also had a hard time getting a PS namespace going inside of c sharp, but was able to get that going late last night locally and then modified it to work remotely. I will post those functions for reference here when I get back to work on Monday and compare what I'm doing to powershell girls code.
|
|
|
|
|
I am looking for more information on how to prevent thread starvation/blocking/racing in an application or service that could possibly running up to 200 threads simultaneously across multiple processors/cores.
Most of the examples I have found online show how to coordinate between 3 or 4 threads max and I am planning a app that will have hundreds.
I've made applications that have run up to 30 threads but when going way beyond that I am worried about some threads not getting any CPU time not to mention synchronization.
Where can I find some really good articles and blogs?
What are the best books on the subject?
There are a lot of books and articles on the subject, I am looking for the most informative and instructional but not presented in an engineering language above my understanding.
I originally posted this on the Q and A forum and it was suggested that I also imply about it on the C# forum.
All suggestions are appreciated.
|
|
|
|
|
I suppose I have to be the typical "that" guy but...
Why do you suppose you need 200 threads? You do realize that dividing work, once you reach the number of cores you may be degrading performance instead of improving it? More threads does not mean more throughput, I suppose I don't know what you are really trying to do, but maybe a good design review is needed before starting down a rather disappointing path...
|
|
|
|
|
I am working on a modular processing model and I was thinking scalability. My current model would be for 20-40 threads. However, if the job became very large scale like processing millions of records every hour, how could I expand the scale while still giving each thread its own slice of CPU time and not having any threads get starved out.
|
|
|
|
|
Without knowing more about your problem space:
I'd suggest building a queue (or queues) of the different types of processing (items in the queue are the data for a given processing type) and having threads that loop around: remove item from the queue and process it. As long as there is something in the queue, the threads will do work. When there's nothing there, there's no work to do.
Determine the number of threads (by experimentation(?) on your hardware) that gives near-optimal performance.
It's possible that if things are IO bound or processed off-the-box (e.g., SQL server) the best number of threads will be more or less than the number of cores.
(Or have the application try to self-tune?)
|
|
|
|
|
That's really kind of where I am going. This is more of experiment to see if creating a modular processing scheme is worth the trouble. I've got some base classes created and was taking the idea to it's endgame. That's why I was asking about thread starvation. In a system that would be processing information sequentially but in an assembly-line fashion, what would it take to prevent threads from being starved out if the system grew to over 200 threads.
|
|
|
|
|
As has been pointed out by others, adding threads isn't free.
At some point the management of the threads and switching between them becomes significant in the big picture.
|
|
|
|
|
Just use the .NET Threadpool or task parallel library
Does the queuing for you
|
|
|
|
|
Or more specifically the servers that run the internet you need to goto an event drive process. One thread per core each doing work when available.
|
|
|
|
|
That's why those servers don't run on Windows; it does not let you hog the machine using a few threads. It's the OS that manages them, and under Windows, all threads are equal.
If it weren't, then some software-vendors that are known to put their apps in the startup-folder would try to have exclusive access to a core, just to have a "fast application".
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
With that many threads your CPU/OS will be overloaded just trying to control and switch them. A very bad idea.
Veni, vidi, abiit domum
|
|
|
|
|
Foothill wrote: I am worried about some threads not getting any CPU time Why? Open the task-manager, and see how many threads are running in the various apps on your system. My browser is aleady above 30, with me having opened 3 tabs.
Windows decides "when" a thread gets put on a core, and how much time it'll get. Unless you muck with their priorities, they'd be equally important.
Foothill wrote: not to mention synchronization. Works the same as with 30 threads.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
You have obviously never worked as a TA, thirty is a hard-codeable number : )
Eddy Vluggen wrote: Works the same as with 30 threads.
|
|
|
|
|
I am looking for documentation for how to have 50+ threads running under a single process in a high throughput application and not have threads be starved. Synchronization would be handled through design. I would like to be able to take multithreading and parallelism to their logical limits.
|
|
|
|
|
"Multi-threading and parallelism to their logical limits"
Then think (literally) outside the box. Taking something "to its limit" is a REALLY poor design...
The newest and greatest parallel processing architecture is distributed processing, using agents on multiple machines (boxes), with a master delegating work. This way you really can have the best of both worlds, throughput, millions of processed data items per second, etc. SETI@home has been doing this since early 2000's, and the concept is catching on. Either you can create a processing farm and not push a machine to its limit, or you can create some kind of public distributed processing system and let people with free idle-time (and even better, free electricity and equipment) do your processing for you.
|
|
|
|
|
First, what makes you think that the number of threads you launch is going to do the job?? Without the cores to support that many, you're just wasting resources and killing throughput, not improving it.
You have to find out what the domain of the problem is first. Why are you launching threads? What causes one thread to take so long processing a single record? Is it a compute-bound problem? Or is it an I/O problem where the thread is stalled, waiting for an I/O operation to complete??
Without knowing the exact causes of the delays in processing a record, throwing threads around will get you nowhere fast. You can throw threads at a stack of records, but if there are not enough cores or enough I/O throughput to run those threads you'll get no benefit. You may have to add hardware to solve the problem, not threads.
But, this is going to take a ton of research to figure out.
|
|
|
|