2019년 9월 17일 화요일

DB - MSSQL - 일별 / 주별 / 월별 / 분기별 날짜 구분




[MSSQL]일별,주별,월별 통계


-- 일단위
Select DATEPART(dd, order_dt), count(order_no) From 주문테이블
group by DATEPART(dd, order_dt)
order by DATEPART(dd, order_dt)



-- 주 단위
Select DATEPART(ww, order_dt), count(order_no) From 주문테이블
group by DATEPART(ww, order_dt)
order by DATEPART(ww, order_dt)



-- 월단위
Select DATEPART(mm, order_dt), count(order_no) From 주문테이블
group by DATEPART(mm, order_dt)
order by DATEPART(mm, order_dt)



-- 년단위
Select DATEPART(yy, order_dt), count(order_no) From 주문테이블
group by DATEPART(yy, order_dt)
order by DATEPART(yy, order_dt)



--분기별
SELECT A.memyear,A.AA,SUM(A.CNT) AS CNT
FROM (
Select DATEPART(yy, regdate) as memyear,DATEPART(mm, regdate) as memmonth,  count(regdate) as cnt
,(CASE DATEPART(mm, regdate) WHEN '1' THEN '1' WHEN '2' THEN '1' WHEN '3' THEN '1'
WHEN '4' THEN '2' WHEN '5' THEN '2' WHEN '6' THEN '2'
WHEN '7' THEN '3' WHEN '8' THEN '3' WHEN '9' THEN '3'
WHEN '10' THEN '4'
WHEN '11' THEN '4'
WHEN '12' THEN '4' ELSE '0' END) AS AA
From SMEM01MEM
group by DATEPART(mm, regdate),DATEPART(yy, regdate)
--order by DATEPART(ww, regdate)
) A
group by A.memyear,A.AA
order by A.memyear,A.AA



2019년 7월 8일 월요일

Cross-Platform : Flutter vs Xamarin







Flutter vs Xamarin: A Developer's Perspective

Mar 18, 2019
In this post, we will compare Flutter and Xamarin. The purpose of this extensive comparison is to provide developers with a basic understanding of both technologies and the differences between them.
Apple and Google have provided native tools and technologies to build apps. iOS app developers can build apps using Xcode and Swift, while Android developers use Android Studio and Kotlin/Java. However, this requires engineers to learn two completely different sets of technologies. As a result, companies have started to adopt cross-platform solutions over the native solutions to build apps for both iOS and Android faster using a single language.
Before Flutter landed in the field of cross-platform mobile application development, there were two popular frameworks in the market: React Native and Xamarin. In our previous post on Flutter vs React Native, we have made an extensive comparison of both frameworks from a developer’s perspective. However, let’s compare Flutter to Xamarin.

Flutter vs Xamarin: Introduction

Flutter and Xamarin are both cross-platform mobile application development frameworks used to build apps using a single code base.
Xamarin was originally founded in 2011 by engineers who created Mono, a cross-platform implementation of Xamarin.Android and Xamarin.iOS. Xamarin was the first cross-platform mobile app development framework where companies can make both Android and iOS apps which look almost native. Later in 2016, Microsoft acquired Xamarin and it became part of Microsoft Visual Studio.
On the other side is Flutter, a project started by Google which they have been heavily promoting since I/O 2017. Both of these technologies help app developers build cross-platform apps faster by using a single programming language. Xamarin has been around since 2011 and is now part of a big Microsoft community, but Flutter has also started seeing huge adoption rates since 2017.
In this post, we will compare Flutter vs Xamarin using ten criteria:
  • Programming language
  • Technical architecture
  • Installation
  • Onboarding and learning curve
  • UI components and development API
  • Developer productivity
  • Community support
  • Testing support
  • App size
  • DevOps and CI/CD support
Now that we have defined all our criteria, let’s start exploring each of them in detail.

Programming language

The key benefit of using a cross-platform mobile app development technology is the ability to use a single programming language to develop apps for both iOS and Android.

Xamarin — C# (.NET)

Xamarin has been using the C# language from day one to build cross-platform apps. C# is a very popular language as it’s been widely used in the Microsoft community since ages. C# has been used to build .NET frameworkssince 2002 and got popular with its cool features like portability, metaprogramming and functional programming.
C# has been used for web development a lot, so the transition from web development to cross-platform mobile development is smooth for C# developers with Xamarin.

Flutter — Dart

Flutter uses the Dart programming language which was introduced by Google in 2011 and is rarely used by developers. Dart syntax is easy to understand for JavaScript or Java developers as it supports most of the object-oriented concepts. It’s easy to get started with Dart as there is a great and easy-to-follow documentation available on the official Dart site here.


Analysis & result

C# is a very popular language as it’s been around for a long time and is backed by Microsoft. There is a huge community of C# developers in the world. Dart also has a great feature set, but it’s rarely used and less known in the developer community. Considering this, it’s clear that Xamarin wins the point in the programming language category.

Technical architecture

When choosing a cross-platform mobile app development framework, it’s essential to consider its technical architecture. By knowing the internals of the framework, we can make an informed decision and choose the one that is better for our project.

Xamarin — Mono

Xamarin uses the Mono execution environment for both iOS and Android platform. In the case of iOS, Mono execution environment runs along with Objective-C runtime and on Unix kernel, while in the case of Android, it runs along with Android Runtime on Linux or other kernel. Microsoft documentation provides a detailed explanation of iOS and Androidarchitecture used with Xamarin. Xamarin also has Swift runtime support, but this lives in a separate repository here and doesn’t seem to be official.

Flutter — Skia

Flutter uses the Dart framework which has most of the components inbuilt, so it’s bigger in size and often does not require the bridge to communicate with the native modules. Dart has so many frameworks, like Material Design and Cupertino, packed inside which provide all the required technologies needed to develop mobile apps. The Dart framework uses Skia C++ engine which has all the protocols, compositions and channels. The architecture of the Flutter engine is explained in detail in GitHub Wiki here.
In short, Flutter has everything needed for app development in the Flutter engine itself.


Analysis & result

The Flutter engine has most of the native components in the framework itself. Xamarin’s Mono execution component also reacts with Java or Objective-C runtime directly and uses most of the native code there. Although Xamarin architecture looks solid, it doesn’t have great support for the Kotlin or the Swift runtime which are official runtimes for developing Android and iOS apps. Flutters wins the architecture battle.

Installation

The installation method should be straightforward without having too many complicated steps so that it could be easily learned by developers that are just starting with it.

Xamarin — Visual Studio (Xamarin SDK)

Xamarin is usually used with the Visual Studio IDE, Xamarin SDK for iOS and macOS can be installed into Visual Studio afterwords. The step-by-step installation guide for installing Visual Studio with Xamarin SDK can be found here. There is hardly any documentation or resources about installing or using Xamarin without Visual Studio.

Flutter — Binary download from source

Flutter can be installed by downloading the binary for a specific platform from GitHub. In the case of macOS, we have to download the flutter.zip file and add it as a PATH variable.
Flutter should improve the installation method by supporting package managers, like Homebrew, MacPorts, YUM, APT, etc so that users wouldn’t need to perform these extra steps during installation.


Analysis & result

Xamarin installation is totally dependent on the Visual Studio IDE, while Flutter installation can be done via command line. Flutter installation seems to require extra steps for adding the binary to PATH and downloading it from the source code. However, installing Flutter is much more easier and lightweight and Flutter can be installed without any dependency on IDE.

Onboarding and learning curve

The process of setting up the developer machine to use the new framework takes time. It requires lots of configuration of software installations. The technology should have proper documentation to get users up and running.

Xamarin

As Xamarin configuration is heavily dependent on Visual Studio and the Xamarin SDK, the developers who are already familiar with the VS Code can get up and running very quickly. However, Xamarin requires separate configurations for iOS and Android, i.e Xamarin.iOS & Xamarin.Android. The Xamarin getting started guide for iOS and Android explains the onboarding process for new developers, but Xamarin is heavily dependent on Visual Studio. If the developer isn’t from the Microsoft ecosystem, it would mean a longer learning curve to get acquainted with Visual Studio and learning the Xamarin SDK. Xamarin has Xamarin University with loads of guides for smooth onboarding of new developers.

Flutter

The getting started guide for Flutter has detailed information on IDE setup and platform setup for both iOS and Android. You can read all the required setup details on Flutter install for macOS here. On top of this, Flutter has a CLI tool called flutter doctor which can guide developers through the setup. It inspects which tools are installed on the local machine and which tools need to be configured. Once the flutter doctor command is happy, we can carry on with creating a new Flutter app. There is a separate page on how to configure the editors to get going with Flutter. Once all the setup is done, we can create and run a new Flutter app from CLI easily.


Analysis & result

The Flutter getting started guide is much simpler than Xamarin’s as softwares required for onboarding are lightweight and easy to install. Also softwares are not dependent of any proprietary softwares.

UI component and development API

When developing cross-platform mobile apps, support for the native component is key. Without the support for the native component, our app won’t feel like a native app. It’s very important that the framework has an API to access the native modules without any pain.

Xamarin — mature component

Being the oldest cross-platform SDK, Xamarin has solid documentation of its development API. Xamarin supports multiple platforms, like iOS, Android, Forms, macOS, watchOS, tvOS, etc, which in turn have lots of UI components and modules in place for developers to build on. Xamarin also has documentation for developing individual components, like layout, buttons, pop ups, databases, etc.

Flutter — rich in components

The Flutter framework is bundled with UI rendering components, device API access, navigation, testing, stateful management and loads of libraries. This rich set of components removes the need to use third-party libraries. If you get the Flutter framework, it means you will have everything needed for developing mobile apps. Flutter also has widgets for Material Design and Cupertino that allow developers to easily render the UI on both iOS and Android platform.


Analysis & result

With its rich set of documentation and a development API, Xamarin has put itself in a strong position over Flutter. Flutter still has a long way to go to allow developing complex UIs, animations and games. On the other hand, Xamarin also supports more platforms than Flutter.

Developer productivity

Developer productivity is the key to building apps faster. In this regard, it’s very important to be able to focus on app development without any kind of wait or distraction.

Xamarin

Xamarin has loads of modules and a great development API; however, it heavily depends on the Visual Studio IDE. Developers from the non-Microsoft stack will struggle to learn all the concepts of VS Code or a similar IDE. Also, learning C# will be require a long learning curve. And when compared to editors, IDEs are heavy-weight and building and compiling things takes time. Xamarin uses AOT compilation for iOS for the build and JIT/AOT for Android, so getting the UI changes in the devices might take some time. Xamarin renders UI in terms of the nativeUIControllers. There are a lot of resources online for Xamarin developers to solve the common issues.

Flutter

Flutter has the hot reload feature and it’s very easy to get started with the demo app. However, as the complexity of apps grows, developers would need to learn and adopt new Flutter concepts. In addition, Dart is not a common programming language and there is a lack of support for it in many IDEs and text editors.


Analysis & result

Being a mature framework, Xamarin has great developer support in terms resources and tools. Flutter is fairly new at this point, but will catch up very soon as the community around Flutter grows.

Community support

As soon as developers start to show interest in a technology and adopt it in their development process, they form a community to share knowledge. A strong community helps developers to learn from each other and solve the problems they are facing.

Xamarin

Xamarin has a huge community spread all over the world. There are community forums to discuss problems, issues and proposals. Also, Xamarin has a Twitter handle for all the Xamarin related events. There are some conferences as well for Xamarin-related talks, like Xamarin Developer Summit. Being the oldest cross-platform mobile app development framework, the Xamarin community has more involvement from developers.

Flutter

Flutter has been around for a while, but it gained a lot of attention when Google promoted it in the Google I/O conference in 2017. The Flutter community is growing rapidly these days, meetups and conferences are taking place online. The biggest event happened last year was Flutter Live in December 2018. In short, the Flutter community is growing rapidly; yet, there are still not enough resources for developers to solve common issues.


Analysis & result

The Xamarin community is way bigger than that of Flutter, especially as Xamarin has become so popular in the last few years. The community grows even faster now that Xamarin has been acquired by Microsoft. Flutter is still fairly new although community support is growing rapidly.

Testing support

Writing tests is a great way to get quick feedback on the code. There is always a testing framework associated with every mature technology to allow developers to create unit, integration and UI tests for their apps.

Xamarin

Xamarin supports all kinds of testing within Visual Studio, e.g unit tests and UI tests. Xamarin also has its own cloud test environment for running the tests. Xamarin unit testing can be set up for each individual platform project as mentioned in the docs here. On top of unit testing, Xamarin has dedicated support for UI testing, Xamarin.UITest API. However, Xamarin apps can be tested with other third-party testing frameworks like Appium independently or with native test frameworks like XCUITest or Expresso. You can read more about the testing Xamarin apps in Visual Studio here.

Flutter

Flutter provides a rich set of testing features to test apps at unit, widget and integration level. Flutter has great documentation on testing Flutter apps here, you can also read the about full-stack testing of Flutter apps for detailed information. Flutter has a cool widget testing feature where we can create widget tests to test the UI and run them at the speed of unit tests.


Analysis & result

Both Xamarin and Flutter have great support for testing. However, Flutter wins as it has widget testing support and testing can be performed at multiple levels.

App size

The size of the binary and app are important for the end users. Apps with a large size consume a lot of disk space and users usually hate bulky apps.

Xamarin

Xamarin supports lots of platforms, but the size of the binary is relatively small. However, when Xamarin apps are bundled for release, then the app size gets a bit bigger. There is no code and performance optimization before it is shipped to app stores.

Flutter

Flutter app binaries are usually bigger and the apps are bigger in size in comparison with native iOS & Android apps. As mentioned on the Flutter FAQpage, Flutter core engine takes up 2.7 MB + there is the framework and app code which makes app binaries a bit heavy in size.


Analysis & result

As cross-platform technologies, Flutter and Xamarin both produce big-sized apps, but the Xamarin binaries are smaller than Flutter binaries as per this source, so Xamarin takes the point here.

DevOps & CI/CD support

Releasing mobile apps to the App Store or Play Store is a painful process. It involves the complex task of code signing and correct project configuration. When it comes to cross-platform mobile app development, it gets even trickier.

Xamarin

Xamarin build automation process heavily depends on Microsoft Visual Studio configuration, but there is also a CLI interface for App Center which is known as appcenter-cli to configure the builds from command line. The App Center Build service has solid documentation on how to build and distribute different platforms. Xamarin apps can build on multiple CI/CD services, like App Center, Jenkins or TeamCity. You can read more about the Xamarin Continuous Integration service here. The basic guide for setting up CI/CD pipelines for Xamarin apps using App Center can be found here.

Flutter

Flutter now has an official CI/CD solution Codemagic which allows developers to set up CI/CD with less configuration. Codemagic is dedicated to just Flutter apps, so building and distributing Flutter apps with it is painless. Check Codemagic’s getting started tutorial .However, there are other cloud-based services that can be used for CI/CD for Flutter apps. The CI/CD flow with Travis CI has been mentioned here. Flutter has a strong command line interface. We can create a binary of the app by using the command line tools and following the instructions in Flutter documentation for building and releasing Android and iOS apps. On top of this, Flutter has officially documented the deployment process with fastlane here.


Analysis & result

Flutter has a great build automation tooling and can be used to deploy apps from the command line. Xamarin also has a strong support for the CI/CD, but it’s all in the Microsoft bubble.

Penalty shootout

Now that both Flutter and Xamarin have 5 points, we need a penalty shootout to decide the winner of this game. Let’s have another 5 points to see who will perform better.

Performance

In terms of performance, Flutter is claimed to have a much better performance than Xamarin apps. Xamarin has a profiler which can report the performance issues earlier, but in the end Flutter’s Dart engine sounds more prominent than Xamarin forms as per this post . Also, while developing apps, the hot reload feature of Flutter contributes a lot to the developer productivity. Flutter wins the first point in the performance category.
Winner: Flutter

Time to market / code sharing

Xamarin uses Xamarin.Forms to share code between multiple platforms. Approximately 96% of code can be shared across platforms. This code sharing includes business logic, Data logic and the network layer. Flutter also enables to share lots of code as Flutter uses its own UI components. However, sometimes Flutter developers need to write native code to support a few things that can’t be done with Flutter. Therefore, the time to market for Xamarin might be shorter due to this feature. Xamarin wins in the code sharing challenge.
Winner: Xamarin

Native user experience

Xamarin and Flutter apps look very native. When compared to other cross-platform technologies which basically use features of web technologies, Flutter and Xamarin both produce apps with a look and feel close to native apps. In this challenge, we can’t pick a winner, so it’s a tie.
Winner: N/A

Price / open source

Although Xamarin has some cool features, it available for free with limitations. Xamarin is developed behind the doors, so you won’t get some native features, like 3D-touch, Force touch etc, straight away. On the other hand, Flutter is open source and developed openly. Flutter has a big advantage in that its code is open source and developers can have proper control over the code. Flutter wins this challenge.
Winner: Flutter

Future

Flutter has a great road map and is growing fast. With capabilities like IDE flexibility, cool features, and widget availability, Flutter seems to have a bright future. Xamarin is still growing, but it’s more for the developers in the Microsoft bubble. Well, we can’t predict the future, so let’s not decide the winner for this challenge.
Winner: N/A
Now, we have a winner and it’s Flutter.

Conclusion

Xamarin and Flutter are two players in the cross-platform mobile development market, both of which enable to produce native-like mobile apps from the same codebase. In this post, we have extensively compared both technologies based on different criteria from a developer’s perspective. Well, this comparison guide is for reference purpose and deciding on which framework to choose may vary from project to project. However, it’s true that Flutter has entered the industry very strongly.


출처 : https://blog.codemagic.io/flutter-vs-xamarin-a-developer-s-perspective/



[Flutter 문서]

https://flutter-ko.dev/docs








2019년 4월 12일 금요일

C# - 크로스 스레드 (Control.Invoke)


C# - 크로스 스레드 (Control.Invoke)



매 1초 마다 현재 시각을 표시하는 간단한 시계를 만든다고 합시다.


2009-05-07 오전 10:44:28


보통은 System.Timers.Timer 나 System.Threading.Timer, 혹은 System.Windows.Forms.Timer 를 사용하겠지만, 여기서는 Thread.Sleep 메서드를 이용하여 매 1초 마다 시간을 표시하는 방법을 사용해 보겠습니다.



protected override void OnShown(EventArgs e)
{
    base.OnShown(e);
    while (true)
    {
        DisplayDateTime();
        Thread.Sleep(1000);
    }
}

private void DisplayDateTime()
{
    label1.Text = DateTime.Now.ToString();
}


실행하면, 시작하자 마자 바로 화면이 먹통이 되어버리는 걸 알 수 있습니다.
Thread.Sleep 메서드가 현재 메서드(UI가 생성된 메서드)를 잡고 있는 이른바 UI 블로킹이 일어난 것인데요. 이를 해결하기 위해서는 이 부분을 별도의 스레드에서 실행하여야 합니다.



private Thread _thread;
protected override void OnShown(EventArgs e)
{
    base.OnShown(e);
    _thread = new Thread(StartNewThread);
    _thread.Start();
}
protected override void OnClosing(CancelEventArgs e)
{
    _thread.Abort();
    base.OnClose(e);
}
private void StartNewThread()
{
    while (true)
    {
        DisplayDateTime();
        Thread.Sleep(1000);
    }
}
private void DisplayDateTime()
{
    label1.Text = DateTime.Now.ToString();
}


1초를 기다린 후 라벨에 시각을 표시하는 로직이 별도의 메서드(StartNewThread)로 빠졌고, 이 메서드는 이제 메인 스레드(UI 스레드)와는 별개의 스레드에서 실행됩니다.
실행을 해 봅시다. 디버깅하지 않고 시작(CTRL + F5)을 실행하면 (운이 좋다면) 문제 없이 시계가 동작하는 걸 볼 수 있지만, 디버깅 시작(F5)을 실행하면 label1.Text = DateTime.Now.ToString();
에서 InvalidOperationException가 발생합니다.


일명 크로스 스레드 예외라고 하는데요.
label1.Text = DateTime.Now.ToString(); 에서 라벨 컨트롤에 접근을 하려고 하는데, 문제는 이 코드가 실행되는 스레드가 라벨 컨트롤이 생성된 스레드(메인 스레드, UI 스레드)가 아니라는 것입니다.

Control.Invoke를 호출하는 방법과 BackgroundWorker를 사용하는 두 가지 방법이 있을텐데, 대부분의 경우에는 BackgroundWorker 가 좋은 선택이 될 것입니다.
스레드 간에 상태를 공유하고, 진행상황을 보고하고, 작업을 중지하는 등 스레드와 관련한 대부분의 작업이 이미 구현되어 있기 때문에 편리하게 사용할 수 있습니다.
다만 BackgroundWorker에는옥의 티랄까, 한 가지 알려진 버그가 있습니다.
이 포스트의 주제가 BackgroundWorker가 아니고, 또 BackgroundWorker에는 곁다리로 슬쩍 이야기할 수 있는 수준 이상의 논점이 많으니까, 이 포스트에서는 Control.Invoke에 대해서만 이야기하도록 하겠습니다.

Control.Invoke를 호출하여 크로스 스레드 문제를 해결하는 코드는 다음과 같습니다.


private void StartNewThread()
{
    while (true)
    {
        if (label1.InvokeRequired)
            label1.Invoke(new DisplayDateTimeHandler(DisplayDateTime));
        else
            DisplayDateTime();
        Thread.Sleep(1000);
    }
}
private delegate void DisplayDateTimeHandler();


먼저 라벨의 InvokeRequired 를 체크하여 Invoke가 필요한지를, 즉 컨트롤에 접근하는 스레드와 컨트롤이 생성된 스레드가  다른 스레드인지를 체크합니다.
굳이 Invoke가 필요하지 않다면 (비록 미미하더라도) 비용이 드는 Invoke를 호출할 필요가 없을 것입니다.
Control.Invoke의 시그니처는 다음과 같습니다.


public Object Invoke(Delegate method, params Object[] args)


첫번째 매개변수가 추상 클래스인 Delegate입니다.
따라서 label1.Invoke(new Delegate(DisplayDateTime)); 과 같이 대리자 인스턴스를 생성할 수가 없습니다.
대신 DisplayDateTimeHandler 라는 대리자 형식을 정의한 후 이 인스턴스를 전달하여야 합니다.
이제 실행(디버깅)을 하여 보면 크로스 스레드 문제 없이 잘 동작합니다.

크로스 스레드 문제가 해결되었으니 여기서 포스트가 끝나야 할 것 같지만, 이 포스트를 서야겠다고 생각한 이유는 사실은 지금 부터 시작 합니다.
Control.Invoke를 호출하는 위 코드를 Action 대리자와 확장 메서드를 사용하여 필드에서 사용할 만한 라이브러리로 만들어 봅시다.

닷넷 프레임웍 2.0에 추가된 두 가지 제네릭 대리자를 사용하면 대부분의 경우에는 대리자를 작성할 필요가 없습니다.
Func과  Action 대리자가 그것인데요. Func은 반환값이 있지만 Action은 반환값이 없다는(void) 점 외에는 동일하며, 두 대리자 모두 매개변수가 0개 ~ 4개인 오버로드가 각각 준비되어 있습니다.
(정확하게 이야기하자면, 매개변수가 0개인 Action 대리자의 형은 void Action() 이므로 제네릭 대리자는 아닙니다.)
그래서 매개 변수가 4개가 넘지 않는 시그니처를 가지는 대리자는 이 두 대리자로 표현할 수가 있는 것입니다.
위 코드에서도 DisplayDateTimeHandler 대리자를 따로 정의하지 않고 제네릭 대리자를 사용할 수 있습니다.
반환값이 없고 매개변수도 없으니까, 제네릭이 아닌 Action 대리자를 사용하면 되겠습니다.


private void StartNewThread()
{
    while (true)
    {
        if (label1.InvokeRequired)
            label1.Invoke(new new Action(DisplayDateTime));
        else
            DisplayDateTime();
        Thread.Sleep(1000);
    }
}


이번에는 확장 메서드를 사용하여 위 코드를 캡슐화 해봅시다.
ControlExtensions라는 static 클래스를 만들고 아래와 같은 확장 메서드를 추가합니다.



public static class ControlExtensions
{
    pubilc static void InvokeIfNeeded(this Control control, Action action)
   {
      if (control.InvokeRequired)
         control.Invoke(action);
     else
         action();
   }
    pubilc static void InvokeIfNeeded<T>(this Control control, Action<T> action, T arg)
   {
      if (control.InvokeRequired)
         control.Invoke(action, arg);
     else
         action(arg);
   }
}

(여기서는 매개변수가 0개 ~ 1개인 오버로드만 보이는데, 2개 ~ 4개인 오버로드도 정의해두면 편리합니다.)
이제 StartNewThread 메서드는 아래와 같이 간단해 집니다.

 

private void StartNewThread()
{
    while (true)
    {
        label1.InvokeIfNeeded(DisplayDateTime);
        Thread.Sleep(1000);
    }
}

람다식이나 익명 메서드를 이용하면 DisplayDateTime 메서드도 따로 정의할 필요가 없어 코드가 좀 더 간단해 집니다.



private void StartNewThread()
{
    while (true)
    {
        label1.InvokeIfNeeded( ()=> label1.Text = DateTime.Now.ToString());
        Thread.Sleep(1000);
    }
}

연습 삼아 코드를 약간 고쳐 봅시다.
DisplayDateTime 메서드를 매개 변수를 가지는 형태로 다음과 같이 수정합니다.



private void DisplayDateTime(DateTime dateTime)
{
    label1.Text = dateTime.ToString();
}


그렇다면 이제 라벨의 Invoke 메서드를 호출할 때 현재 시각을 매개 변수로 넘겨야 합니다.



private void StartNewThread()
{
    while (true)
    {
        label1.InvokeIfNeeded(DisplayDateTime, DateTime.Now);
        Thread.Sleep(1000);
    }
}


ControlExtensions.InvokeIfNeeded 오버로드 중,


pubilc static void InvokeIfNeeded<T>(this Control control, Action<T> action, T arg)


가 호출되는데, 이는 다시 control.Invoke(action, arg); 를 호출합니다.
Control.Invoke의 두 번째 매개변수는 params object[] 이기 때문에, action 대리자의 매개변수의 갯수가 형에 상관없이 호출이 가능합니다.


출처: https://kimgwajang.tistory.com/193





javascript - SQL 예약어 제거

  <script language="javascript"> //특수문자, 특정문자열(sql예약어) 제거 function checkSearchedWord(obj){ obj.value = obj.value+&quo...