2016년 8월 30일 화요일

c# asnyc await example Simple notation



private void button1_Click(object sender, EventArgs e)
{
Console.WriteLine("in ");
method1();

//Thread.Sleep(1000);
Console.WriteLine( "out");

}

async void method1()
{
Console.WriteLine("in method1");
await Task.Run(() => awmethod() );
Console.WriteLine("out method1");
}

void awmethod()
{
Thread.Sleep(3000);
Console.WriteLine("Here Here");
}

----------------------




private void button1_Click(object sender, EventArgs e)
{
Console.WriteLine("in ");
method1();

//Thread.Sleep(1000);
Console.WriteLine( "out");

}

async void method1()
{
Console.WriteLine("in method1");
await getmethod();
Console.WriteLine("out method1");
}

void awmethod()
{
Thread.Sleep(3000);
Console.WriteLine("Here Here");
}

Task getmethod()
{
Task task = Task.Run(() => awmethod());
return task;
}

----------------------



private void button1_Click(object sender, EventArgs e)
{
Console.WriteLine("in ");
method1();

//Thread.Sleep(1000);
Console.WriteLine( "out");

}

async void method1()
{
Console.WriteLine("in method1");
await getmethod();
Console.WriteLine("out method1");
}

void awmethod()
{
Thread.Sleep(3000);
Console.WriteLine("Here Here");
}

Task getmethod()
{
Task task = new Task(() => awmethod());
task.Start();

return task;
}

c# await 로 비동기 Example

public async void TempSaveGrabData(byte[] inputArr, int buffNum, int scanNum)
{
await TempSaveMethodTask(inputArr,buffNum,scanNum);
Console.WriteLine( "{0} Scan and {1} Buff is Save in C:", scanNum,buffNum);
}

public Task TempSaveMethodTask(byte[] inputArr, int buffNum, int scanNum)
{
Task tempSaveTask = new Task(() => TempSaveMethod(inputArr, buffNum, scanNum));
return tempSaveTask;
}

void TempSaveMethod(byte[] inputArr, int buffNum, int scanNum)
{
string path = "c:\\ImageTemp\\" + scanNum.ToString("D3") + "_" + buffNum.ToString("D3") + ".dat";
Stream outStream = new FileStream(path, FileMode.Create);
outStream.Write(inputArr, 0, inputArr.Length);
outStream.Dispose();
}


여기선 데이터를 받으면 데이터를 하드에 저장을 하는데, 이 저장을 하는 작업을 하는동안 메인 쓰레드가 안멈추길 바란다.
await 로 쓰는동안 제어권을 호출한 메소드에 다시 넘겨준다.

c# Task async await example 2

private async void button1_Click(object sender, EventArgs e)
{

int result = await inttask();
label1.Text = result.ToString();
}

public async Task inttask()
{
Task temptak = new Task(method);
temptak.Start();
int output = await temptak;
return output;
}

int method()
{
Thread.Sleep(4000);
return 999;
}


4초동안 계산을 하는데, 윈폼은 활성화 되있는 상대고, 계산이 끝나면 라벨에 결과가 표시가 된다.

-> 다음은 마우스 클릭 이벤트를 계산이 끝나기 전에 눌렀을떄 어떻게 되나 보자.

private async void button1_Click(object sender, EventArgs e)
{
Console.WriteLine("event out");
int result = await inttask();
label1.Text = result.ToString();
Console.WriteLine("Txt change");
}

public async Task inttask()
{
Task temptak = new Task(method);
temptak.Start();
int output = await temptak;
return output;
}

int ttt = 100;
int method()
{
ttt = ttt * 2;
Thread.Sleep(4000);
return ttt;
}

보면 큐에 쌓인다.

5번 누르면 5번 결과가 바뀐다. 하지만 누른 시간차만큼 바뀌는데 시간이 걸림.

c# Task Async Await Basic Example




private void button1_Click(object sender, EventArgs e)
{
Mymethodasync();
}

public async Task Mymethodasync()
{
Console.WriteLine("1");
Task llrr = longrun();
Console.WriteLine("2");
int output = await llrr;
Console.WriteLine("3");

}

public async Task longrun()
{
Console.WriteLine("longrun Task");
await Task.Delay(1000);
Console.WriteLine("longrun Task Done");
return 1;
}

2016년 8월 23일 화요일

c# Event

http://mrw0119.tistory.com/21

좋은 설명

C# 여러개의 매소드를 순차적으로 실행할때


만약 각 매소드들의 매개변수가 같으면 델리게이트 체인을 이용한다.

EX)

public class testclass
{
public delegate int calc(int a, int b); // 델리게이트 선언 (클래스와같은 형선언, 단지 매개변수만 형태 지정이 가능하다.)

public int chain()
{
calc deleInstance = new calc(method1); // 단순히 델리게이트지정

calc chaindele = (calc)Delegate.Combine(new calc(method2),new calc(method3)); // 델리게이트 체인 지정으로 매소드2,3 이 순차적으로 실행된다.

int output = caindele(20,10);

}


public int method1(int input, int input2)
{
int output = input + input2;
return output;
}

public int method2(int input, int input2)
{
int output = input * input2;
return output;
}
public int method3(int input, int input2)
{
int output = input - input2;
return output;
}




}

c# Assertion

http://illef.tistory.com/entry/Beyond-the-Assertion-Code-Contract-1

C# Pointer


http://hbesthee.tistory.com/1163


Ex :

public byte[] DataTransFromBuffer(SapBuffer buff)
{
try
{
byte[] output = new byte[buff.Width * buff.Height];
GCHandle pinnedArray = GCHandle.Alloc(output, GCHandleType.Pinned); // make
IntPtr pointer = pinnedArray.AddrOfPinnedObject();
buff.ReadRect(0, 0, buff.Width, buff.Height, pointer);
Marshal.Copy(pointer, output, 0, output.Length);
pinnedArray.Free();
return output;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return null;
}
}

2016년 8월 10일 수요일

C# 레지스트리에 설정파일 저장 변경 로드 테스트

먼저 Regedit 에서

HKEY_CURRENT_USER\SOFTWARE\ZTest 로 키를 생성

(키 생성하면 폴더가 생성됨)

안에 DogName 와 Age 를 스트링으로 생성한다.


void Load()
{
String Keypath = "Software\\ZTest";
RegistryKey regkey = Registry.CurrentUser.OpenSubKey(Keypath);
if (regkey != null)
{
Path = regkey.Name;
item1 = (string)regkey.GetValue("DogName");
item2 = (string)regkey.GetValue("Age");
}
}


void Save()
{
String Keypath = "Software\\ZTest";
RegistryKey regkey = Registry.CurrentUser.OpenSubKey(Keypath);
if (regkey != null)
{
Path = regkey.Name;
regkey.SetValue("DogName","Not mimi");
regkey.SetValue("Age","not 12");
}
}

2016년 8월 4일 목요일

C# for loop with no int i

Decimal.Round() -> decimal point 2




string 보너스

doublet = 10234.234;
Console.WriteLine(t.ToString("#,#.###"));


소수점에 대한 글

http://www.mkexdev.net/Article/Content.aspx?parentCategoryID=2&categoryID=9&ID=98

2016년 8월 3일 수요일

c# PictureBox Real Position on Not Scaled Image

Point controlRelative = pictureBox1.PointToClient(MousePosition);
Size imageSize = pictureBox1.Image.Size;
Size boxSize = pictureBox1.Size;

Point imagePosition = new Point((imageSize.Width / boxSize.Width) * controlRelative.X,
(imageSize.Height / boxSize.Height) * controlRelative.Y);

2016년 8월 2일 화요일

c# Task Func Return Value Net4.5 Style




NET 4.5

The recommended way in .NET 4.5 is to use Task.FromResult, Task.Run or Task.Factory.StartNew:

--FromResult:

public async Task DoWork()
{
int res = await Task.FromResult(GetSum(4, 5));
}

private int GetSum(int a, int b)
{
return a + b;
}


Please check out Stefan’s comments on the usage of FromResult in the comments section below the post.

--Task.Run:


public async Task DoWork()
{
Func function = new Func(() => GetSum(4, 5));
int res = await Task.Run(function);
}

private int GetSum(int a, int b)
{
return a + b;
}


--Task.Factory.StartNew:


public async Task DoWork()
{
Func function = new Func(() => GetSum(4, 5));
int res = await Task.Factory.StartNew(function);
}

private int GetSum(int a, int b)
{
return a + b;
}


=========================== My Code ===================
Action actone;
Func funcone;
Action acttwo;


private async void pictureBox1_MouseClick(object sender, MouseEventArgs e)
{
int posX = e.X;
int posY = e.Y;

actone = ActMethod;
funcone = ActMethod3;
acttwo = ActMethod2;

await Task.Factory.StartNew(() => actone());
await Task.Factory.StartNew(actone);
await Task.Factory.StartNew(() => acttwo(posX, posY));

string reu = await Task.FromResult(funcone(posX, posY));

string result = await Task.Run(() => funcone(posX, posY));
}

void ActMethod()
{
Console.WriteLine("done");
}

void ActMethod2(int posX, int posY)
{
Console.WriteLine("done");
}

string ActMethod3(int posX, int posY)
{
Console.WriteLine("done");
return "func done";
}

c# 비동기 Task.Factory.StartNew 사용

1. 메소드 만듬

2. 매소드를 가지고 Action 만듬

3. 테스크에 Action 집어넌다.

= 이건 Method 에 Input Parameter 가 있을때

Action acttwo;

private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
{
int posX = e.X;
int posY = e.Y;


acttwo = ActMethod2;
Task.Factory.StartNew(() => acttwo(posX,posY));
}

void ActMethod2(int posX, int posY)
{
Color inten = bitmp.GetPixel(posX, posY);
byte bt1 = inten.B;
for (int i = posX; i < posX + 200; i++) { linelist.Add(bitmp.GetPixel(i, posY).R); } Console.WriteLine("done"); } = 이건 Input Parameter 가 없을때 Action actone; private void pictureBox1_MouseClick(object sender, MouseEventArgs e) { int posX = e.X; int posY = e.Y; actone = ActMethod; Task.Factory.StartNew(actone); // 이거나 Task.Factory.StartNew(() => actone()); // 이거 쓴다
}

void ActMethod()
{

Console.WriteLine("done");
}

Fast Method of Bitmap To GrayScale



public static Bitmap MakeGrayscale3(Bitmap original)
{
//create a blank bitmap the same size as original
Bitmap newBitmap = new Bitmap(original.Width, original.Height);

//get a graphics object from the new image
Graphics g = Graphics.FromImage(newBitmap);

//create the grayscale ColorMatrix
ColorMatrix colorMatrix = new ColorMatrix(
new float[][]
{
new float[] {.3f, .3f, .3f, 0, 0},
new float[] {.59f, .59f, .59f, 0, 0},
new float[] {.11f, .11f, .11f, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {0, 0, 0, 0, 1}
});

//create some image attributes
ImageAttributes attributes = new ImageAttributes();

//set the color matrix attribute
attributes.SetColorMatrix(colorMatrix);

//draw the original image on the new image
//using the grayscale color matrix
g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height),
0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);

//dispose the Graphics object
g.Dispose();
return newBitmap;
}

c# Wait 관련

1. 테스크를 병렬로 사용한다
Task.WaitAll(
Task.Factory.StartNew(()=>DoSomething()),
Task.Factory.StartNew(()=>Thread.Sleep(200))
);

2.스톱워치 사용 : 매우 정확함. 스톱워치 시작, 작업, 대기 ->
private void Wait(double milliseconds)
{
long initialTick = stopwatch.ElapsedTicks;
long initialElapsed = stopwatch.ElapsedMilliseconds;
double desiredTicks = milliseconds / 1000.0 * Stopwatch.Frequency;
double finalTick = initialTick + desiredTicks;
while (stopwatch.ElapsedTicks < finalTick)
{

}
}

private void btnRight_Click(object sender, RoutedEventArgs e)
{
currentPulseWidth = 0;

//The stopwatch will be used to precisely time calls to pulse the motor.
stopwatch = Stopwatch.StartNew();

GpioController controller = GpioController.GetDefault();

servoPin = controller.OpenPin(13);
servoPin.SetDriveMode(GpioPinDriveMode.Output);


// Here is how you would move the motor. Call a funciton like this when ever you are ready to move motor
MoveMotor(ForwardPulseWidth);

Wait(3000); //wait three seconds

//move it backwards
MoveMotor(BackwardPulseWidth);

}