关于线程的问题以及是否有必要。 [英] Question about threads and whether it is necessary.

查看:97
本文介绍了关于线程的问题以及是否有必要。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天,



我这里有一个相当简单的问题。我是线程的新手,想知道是否在我的下面的场景中使用它。



基本上我有一个尚未测试的C#程序。程序运行时,它会使用对服务器的API调用向不同的手机发送批量短信。发送需要对发送到的每个号码进行呼叫。这显然意味着一个foreach循环。



我的第一个问题是:

当程序执行此代码时,它是否会锁定主该程序的窗口,并阻止用户对该程序进行其他工作?用户是否需要等待发送完成?



第二个问题:

我应该使用一个线程来运行该方法吗?背景还是我误解了线程的重点?在没有表格锁定的情况下还有另一种方法吗?



如果这些是简单的问题,请原谅我,但想简单地学习并找到更多的见解。



问候



我尝试过:



我试过阅读有关线程的文章,但无法弄清楚这是否正是我需要的

解决方案

引用:

当程序执行此代码时,它是否会锁定程序的主窗口并阻止用户对程序进行其他工作?用户是否需要等待发送完成?



是的。是的。



Quote:

我应该使用Thread来运行该方法在后台还是我误解了线程的重点?有没有其他方法可以在没有表格锁定的情况下这样做?



是的,不,你不是误会。并且没有。



可能,我设置了一个线程来进行实际发送,并从Queue< T>中提供它。通过锁。如果队列中有某些内容,则线程获取它,处理它并再次检查。当它为空时,线程会进入休眠状态一秒钟或一分钟然后再次检查。



引用:

感谢您的澄清。线程似乎令人生畏,在互联网上显示了很多不同的方式。我尝试做简单的线程autoSend = new Thread(_viewModel_API.SendMessagesToListOfClients()) ;



但我显然错过了这背后的全部逻辑,因为没有发送任何信息。(此时它应该只弹出一条消息进行测试)





试试这个:

 private void myButton_Click(object sender,EventArgs e)
{
线程worker1 =新线程(MyMethod);
worker1.Start(你好);
线程worker2 =新线程(MyMethod);
worker2.Start(Hello There);
线程worker3 =新线程(MyMethod);
worker3.Start(Hello There Again);
}

private void MyMethod(对象消息)
{
string s = message as string;
if(s!= null)
{
Console.WriteLine(s);
Thread.Sleep(5000);
Console.WriteLine({0} - 已完成,s);
}
}



启动三个线程,它们使用不同的数据执行相同的操作。

你得到这样的东西:

你好
你好有
你好再次
线程0x15c8退出代码259(0x103 )。
线程0x7ac已退出,代码为259(0x103)。
线程0x1e2c已退出,代码为259(0x103)。
你好 - 完成了
你好再来一次 - 完成
你好 - 完成



我不建议你那样做 - 您需要一个接一个地发送消息,而不是一次性发送消息,因为您只有一个设备发送它们。所以你需要一个带有循环的额外线程,但是这应该给你一个想法。

注意,在这个例子中,线程没有按照它们的启动顺序完成 - 那是因为Windows是一个多任务系统。


引用:

当程序执行此代码时,它会锁定程序的主窗口并阻止用户对程序进行其他工作吗?用户是否需要等待发送完成?

OG有点短,答案很长,任何需要I / O操作的操作 - 包括但不限于网络I / O,磁盘I / O等甚至加载图像位图将是一个原因 - 总是会导致您的应用程序冻结。这是因为控件已转移到控制I / O操作的程序集,您的应用程序必须等待该操作完成才能实际执行其他操作,例如尤其处理用户交互。大多数情况下,解决方案只是以下函数结构的一种情况,

  public   async   void  IOFunction(){
// 代码..
// 几乎每个对象在.NET和WinRT中具有异步功能
await Obj.DoJobAsync();
// 代码。
}



这样,您将能够处理用户交互并仍然在后端执行I / O任务。这类似于特殊的,线程任务 BackgroundWorker 对象,但以更简单的方式。



更多信息:使用异步和异步编程进行异步编程等待(C#) [ ^ ]

Quote:

我应该使用Thread在后台运行该方法还是我误解了这一点线程?有没有其他方法可以在没有表单锁定的情况下执行此操作?

OG所说的是准确的,但我不建议仅依赖于此。而不是那样,我建议你自己不要使用 Thread 。而不是那样,只需使用任务对象。我的建议是简单地采用异步/等待编程模式。无需深入 Thread ,或使用任务或使用 BackgroundWorker 对象或为此创建自己的机制。 C#处理异步任务的方式非常方便,自从我开始使用它以来,我个人很享受我的生活。



免责声明:由于双功能声明结构,异步/等待模式对于初学者来说真的很难。但是一旦你理解了它,它对你来说将是惊人的。忘记线程,你根本不必使用它们。


Good day,

I have a rather simple question here. I am new to threads and was wondering whether to use it with my below scenario.

Basically I have a C# program that is not tested yet. When the program runs, it will send bulk sms messages to different cellphones using API calls to a server. The sending requires the call to be made for each number being sent to. This obviously means a foreach loop.

My first question is this:
When the program executes this code, will it lock up the main window of the program and prevent the user from doing other work on the program? Will the user need to wait for the sending to complete?

Second Question:
Should I use a Thread to run the method in the background or am I misunderstanding the point of a Thread? Is there another way of doing this without the form locking up?

Forgive me if these are simple questions, but simple seeking to learn and find more insight in this.

Regards

What I have tried:

I have tried reading through articles about threads, but cannot figure out whether this is exactly what I need

解决方案

Quote:

When the program executes this code, will it lock up the main window of the program and prevent the user from doing other work on the program? Will the user need to wait for the sending to complete?


Yes. And yes.

Quote:

Should I use a Thread to run the method in the background or am I misunderstanding the point of a Thread? Is there another way of doing this without the form locking up?


Yes, and no, you're not misunderstanding. And no.

Probably, I'd set up a thread to do the actual sending, and feed it from a Queue<T> via a lock. If there is something in the queue, the thread gets it, deals with it and checks again. When it's empty, the thread goes to sleep for a second or a minute and then checks again.

"

Quote:

Thank you for clarification. Threads seems intimidating, showing a lot of different ways of doing it across the internet. I tried doing simply Thread autoSend = new Thread(_viewModel_API.SendMessagesToListOfClients());

But I am clearly missing the entire logic behind this as nothing is sent. (Well at this point it should only pop up a message for testing)

"

Try this:

private void myButton_Click(object sender, EventArgs e)
    {
    Thread worker1 = new Thread(MyMethod);
    worker1.Start("Hello");
    Thread worker2 = new Thread(MyMethod);
    worker2.Start("Hello There");
    Thread worker3 = new Thread(MyMethod);
    worker3.Start("Hello There Again");
    }

private void MyMethod(object message)
    {
    string s = message as string;
    if (s != null)
        {
        Console.WriteLine(s);
        Thread.Sleep(5000);
        Console.WriteLine("{0} - Completed", s);
        }
    }


It kicks off three threads which do the same thing with different data.
And you get something like this:

Hello
Hello There
Hello There Again
The thread 0x15c8 has exited with code 259 (0x103).
The thread 0x7ac has exited with code 259 (0x103).
The thread 0x1e2c has exited with code 259 (0x103).
Hello - Completed
Hello There Again - Completed
Hello There - Completed


I don't suggest that you do it that way - you need to send the messages one after the other not try to send them all at once since you've only got the one device to send them. So you need a single extra thread with a loop in it instead, but that should give you an idea.
Note that in this example, the threads didn't finish in the order they were started - that's to be expected since Windows is a multi tasking system.


Quote:

When the program executes this code, will it lock up the main window of the program and prevent the user from doing other work on the program? Will the user need to wait for the sending to complete?

OG was a bit short, the long answer is, any operation that requires an I/O operation — including but not limited to network I/O, disk I/O etc. even loading the image bitmaps would be a reason here — would always cause your application to freeze. That is because the control has been transferred to the assembly that controls I/O operation and your application will have to wait for that operation to complete before it can actually perform other operations such as "and especially" handling user interaction. Mostly, the solution is simply a case of the following function-structure,

public async void IOFunction() {
   // Code..
   // Almost every object has async functionality in .NET and WinRT
   await Obj.DoJobAsync();
   // Code.
}


This way, you will be able to handle the user interaction and still perform I/O task at the backend. That is similar to having special, Thread, Task or BackgroundWorker objects but in a much simpler way.

For more: Asynchronous Programming with async and await (C#)[^]

Quote:

Should I use a Thread to run the method in the background or am I misunderstanding the point of a Thread? Is there another way of doing this without the form locking up?

What OG said is accurate, but I don't recommend relying on that only. Instead of that, I would recommend not-to-use Thread yourself. Instead of that, just use a Task object. My recommendation is to simply embrace async/await pattern of programming. There is no need to go in the depths of Thread, or using Task or using BackgroundWorker object or to create your own mechanism for this. C#'s way of handling asynchronous tasks is really handy and I have personally enjoyed my life ever since I started using it.

Disclaimer: Async/await pattern is really tough for beginners because of bi-function-declaration structure. But once you understand it, it will be amazing for you. Forget about threads, you don't have to use them at all.


这篇关于关于线程的问题以及是否有必要。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆