2016년 8월 2일 화요일

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);

}

2016년 7월 27일 수요일

c# winform - acess controller in sub thread BeginInvoke((Action)(() => ControllerAcess ));


btnScan => Main Thread

메인스레드가 아닌곳에서 접근할려면 이렇게 하면 된다.

btnScan.BeginInvoke((Action)(() => btnScan.Enabled = true));


예를 들어

Thread tr;
private void button2_Click(object sender, EventArgs e)
{
tr = new Thread(method);
tr.Start();
}

private void method()
{
button1.Enabled = false;

button1.BeginInvoke((Action)(() => button1.Enabled = true));

Action act = new Action(invokemethod);
button1.BeginInvoke(act);

button1.BeginInvoke((Action)invokemethod);
}

private void invokemethod()
{
button1.Enabled = false;
}


이 서브 스레드에서 윈폼의 컨트롤러에 접근시 위와 같이 사용

c# winform - acess controller in sub thread


btnScan => Main Thread

메인스레드가 아닌곳에서 접근할려면 이렇게 하면 된다.

btnScan.BeginInvoke((Action)(() => btnScan.Enabled = true));


예를 들어

Thread subthrad = new Thread();

subthread.Start();


이 서브 스레드에서 윈폼의 컨트롤러에 접근시 위와 같이 사용

2016년 7월 17일 일요일

c# timer 사용설명

타이머 생성자 2개를 보자.

1. Timer(TimerCallback)

-새로 만든 Timer 개체를 상태 개체로 사용하고 무한 기간 및 무한 만료 예정 시간을 지정하여 Timer 클래스의 새 인스턴스를 초기화합니다.

2. Timer(TimerCallback, Object, Int32, Int32)

-부호 있는 32비트 정수로 시간 간격을 지정하여 Timer 클래스의 새 인스턴스를 초기화합니다.



------------------ 타이머 생성법 -------------

1. Input 파라미터를 object로 갖는 메소드 생성. (타이머에의해 실행될 메소드)
2. 타이머 생성 이떄 메소드가 Input 파라미터를 사용하는 경우는 2번의 생성자 사용.

Timer(Input파마리터가 object인 메소드, 메소드에 들어가는 Input 파마리터, 시작전 딜레이, 인터벌)




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






void timermethod(object state)
{
Console.WriteLine(state.ToString()); <- 여기서 100만 출력함. Timer의 두번째 Input 파라미터가 100 이므로..
string temp2 = stage.GetPosition();
}


private void button1_Click(object sender, EventArgs e)
{
System.Threading.Timer timear = new System.Threading.Timer(new TimerCallback(timermethod), 100, 0,100);
temp1 = stage.GetPosition();
for (int i = 0; i < 4; i++)
{
stage.MoveAbsPosXX(40000);
stage.GetPosition();
stage.MoveAbsPosXX(1000);
stage.GetPosition();
}
}






2016년 7월 14일 목요일

C# winform (윈폼)에서 크로스 스레드 관리. Invoke 사용법


1. 크로스 스레드가 나는걸 생각한다. (ex. 윈폼의 컨트롤들. 얘네는 윈폼 생성시 어떤 스레드가 다 처리한다. 이 스레드를 스레드1 이라고 한다.)

2. 크로스 스레드가 나는 애들. 즉 윈폼의 컨트롤에 접근해서 이용 할려고 할때, 이 일은 스레드1 에게 다 시켜야 한다.

3. 그 외의 것은 스레드 2,3,.. 이 처리해도 된다.


4. 밑의 코드를 보자.

a.버튼 클릭 -> 스레드tr이 Thread_Test1을 실행한다.
b.Thread_Test1을 실행시켜 나가는데 도중에 프로그래스바컨트롤에 접근을 해야되서, 이부분을 스레드1이 처리하게 명령한다. (invoke)
c. progressBar1.Invoke(pro1,new object[] { i}); 이부분이 스레드1이 pro1을 처리하라고 하는부분.
d. pro1은 델리게이트로 progvarCall pro1 = new progvarCall(Thread_Test2);에서 Thread_Test2 가 pro1이다.
e. invoke 는 입력파라미터가 델리게이트 이므로 이렇게 쓴것이다.
f. 그러면 Thread_Test1에서 인보크 부분만 스레드1이 처리하고 나머지는 tr스레드가 처리한다.

즉, tr스레드는 다른거 하고있다가, tr스레드가 호출(인보크) 할때만 Thread_Test2를 실행하고, 끝나면 다시 다른거 하러간다.


public partial class Form1 : Form
{

Thread tr;
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
progressBar1.Minimum = 0;
progressBar1.Maximum = 1000000; //프로그래스의 최대값을 설정
tr = new Thread(Thread_Test1);
tr.Start();
}

delegate void progvarCall(int value);



public void Thread_Test1()
{
progvarCall pro1 = new progvarCall(Thread_Test2);

try
{
for (int i = 0; i < 1000000; i++) // for문을 이용해 프로그래스바의 값을 변경해 줍니다
{
//progressBar1.Invoke(new progvarCall(Thread_Test2),new object[] { i});
progressBar1.Invoke(pro1,new object[] { i}); // 크로스 쓰레드 발생부분만 따로 뺴준다.
//progressBar1.Invoke(pro1); < Invoke 형식 자체가 Invoke(Delegate method, params object[] args) 이다.
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
// 두번째 스레드
public void Thread_Test2(int var)
{
progressBar1.Value = var;
}


}