C# 为什么我的RunWorkerCompleted没有收到RunWorkerCompletedEventArgs?

C# 为什么我的RunWorkerCompleted没有收到RunWorkerCompletedEventArgs?,c#,backgroundworker,.net-4.5,C#,Backgroundworker,.net 4.5,我可以从调试消息中看到,e.Result在整个DoWorker方法中都等于“Success”,但在RunWorkerCompleted方法的开头,e.Result根本不返回任何结果 这是WinForm的_构造 public LicenseValidator() { // Initialize the UI InitializeComponent(); // Start the background worker BackgroundWorker worker =

我可以从调试消息中看到,e.Result在整个DoWorker方法中都等于“Success”,但在RunWorkerCompleted方法的开头,e.Result根本不返回任何结果

这是WinForm的_构造

public LicenseValidator()
{
    // Initialize the UI
    InitializeComponent();

    // Start the background worker
    BackgroundWorker worker = new BackgroundWorker();
    worker.DoWork += new DoWorkEventHandler(worker_DoWork);
    worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
    worker.RunWorkerAsync();

    // Tell debug log that the UI thread is still processing
    Debug.WriteLine("UI thread running");  
}
这是我的工作方法

public async void worker_DoWork(object sender, DoWorkEventArgs e)
{
    // Tell debug log that the worker thread is now running
    Debug.WriteLine("Worker thread running");

    // Define variables
    String HWID = Security.FingerPrint.Value();
    String APIPath = "http://xxxxxxxxx.net/api.php";
    String Serial;
    HttpClient client = new HttpClient();
    HttpResponseMessage response;
    String responseString;

    // Check for license in AppData
    try{
        // Get license path
        String licensePath = Environment.GetEnvironmentVariable("APPDATA") + @"\UniLeech\License.txt";
        // License exists, validate it
        if (File.Exists(licensePath))
        {
            Serial = File.ReadAllText(licensePath);
            Debug.WriteLine(Serial);
            response = await client.GetAsync(APIPath + "?hwid=" + HWID + "&serial=" + Serial);
            responseString = await response.Content.ReadAsStringAsync();
            Debug.WriteLine(responseString);
            dynamic jObj = JsonConvert.DeserializeObject(responseString);
            if (jObj.success == "true")
            {
                Debug.WriteLine("License validation was successful");
                e.Result = "Success";
            }
            else
            {
                e.Result = jObj.error;
            }
            Debug.WriteLine(e.Result);
        }
        // License does not exist, prompt for one
        else
        {
            Debug.WriteLine("License file not found");
            e.Result = "Unregistered";
        }
    }
最后,我的worker\u运行WorkerCompleted方法

public void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    Debug.WriteLine("Worker completed");
    String result = e.Result as String;
    if ((e.Error == null))
    {
        Debug.WriteLine("No errors");
        Debug.WriteLine("Result = " + result);
        if (e.Cancelled)
        {
            Debug.WriteLine("Worker cancelled");
        }
        switch ((String)e.Result.ToString())
        {
            case "Success":
                this.Hide();
                this.ShowInTaskbar = false;
                Main mainForm = new Main();
                mainForm.Show();
                break;

            case "Banned":
                popupError("ERROR: License revoked!",
                           "Your license has been revoked, contact Time Sheep for more information. You can purchase a new one by visiting the ordinary order link."
                          );
                break;

            case "Invalid":
                popupError("ERROR: Invalid serial/HWID",
                           "Either your serial number or hardware identifier was invalid. If you purchased UniLeech, please contact Time Sheep with proof of purchase."
                          );
                break;

            case "Unregistered":
                this.Hide();
                this.ShowInTaskbar = false;
                Register registerForm = new Register();
                registerForm.Show();
                break;

            default:
                MessageBox.Show((string)e.Result, "ERROR");
                break;
        }
    }
}
在执行时,将显示以下调试消息(案例:I有文件,e.结果应为“成功”):


我怀疑问题是由于DoWork方法是异步的,但我不知道如何同步使用HttpClient。

您不能使用
异步的
DoWork
BackgroundWorker
假设当
DoWork
返回时,它已完成


您根本不需要
BackgroundWorker
。只需使用
Task。改为运行

您不能使用
异步
DoWork
BackgroundWorker
假设当
DoWork
返回时,它已完成



您根本不需要
BackgroundWorker
。只需使用
Task。运行

将调用
ToString()
的结果强制转换为
string
似乎有点过头了……我建议您更改此选项:
Debug.WriteLine(result)
Debug.WriteLine(“Result=“+Result”)-这会让事情变得更清楚。@Jon哦,我忘了删除它了吗?。。是的,你是对的,但这是我第一次使用C#程序,只有PHP经验是很困难的,想想PHP的转换矩阵有多复杂。更改它会返回
Result=
我不确定你是否可以在后台工作程序中使用
wait
调用
ToString()的结果
string
似乎有点过头了…我建议您更改此设置:
Debug.WriteLine(结果)
Debug.WriteLine(“Result=“+Result”)-这会让事情变得更清楚。@Jon哦,我忘了删除它了吗?。。是的,你说得对,但这是我第一次使用C#程序,而且只有PHP经验是很困难的,想想PHP的转换矩阵有多复杂。更改它会返回
Result=
我不确定是否可以在后台工作程序中使用
wait
。如果他这样做,他会想更改
File.ReadAllText
以使用异步文件IO。之后,他甚至不需要
任务。运行
,他可以直接从UI线程调用它,因为它不会被阻塞。使用BGW而不是任务有什么缺点吗?我觉得我更了解BGW,我在任务中迷失了方向。@Servy:说得好;他可以使整个事情
异步
@时间表:BGW仍然可用,但基于任务的编程更好。天气很好,而且很好。BGW没有被弃用,但是
async
可以用更短、更易维护的代码和更少的陷阱(例如,我在我的文章中描述的嵌套问题)完成BGW所能做的一切。@TimeSheep当您有长时间运行的CPU限制代码时,BGW是很好的。当您有长期运行的IO绑定代码时,这是无效的,因此使用BGW会使您的代码效率大大降低,因为您需要使用完全阻塞IO方法(或阻塞异步方法)。使用完全非BGW的解决方案可以避免完全阻塞线程。简而言之,这个特定的用例不适合BGW设计用于的模型;尝试强制它是…不推荐的。谢谢你澄清了这一点,我肯定会研究它,但是看到这个程序是多么的微不足道,我不打算重做它来利用任务。我更喜欢从我部分理解的事情开始,即BGW。这只是我为自己设置的一个项目,目的是学习该语言:)如果他这样做,他会想更改
File.ReadAllText
以使用异步文件IO。之后,他甚至不需要
任务。运行
,他可以直接从UI线程调用它,因为它不会被阻塞。使用BGW而不是任务有什么缺点吗?我觉得我更了解BGW,我在任务中迷失了方向。@Servy:说得好;他可以使整个事情
异步
@时间表:BGW仍然可用,但基于任务的编程更好。天气很好,而且很好。BGW没有被弃用,但是
async
可以用更短、更易维护的代码和更少的陷阱(例如,我在我的文章中描述的嵌套问题)完成BGW所能做的一切。@TimeSheep当您有长时间运行的CPU限制代码时,BGW是很好的。当您有长期运行的IO绑定代码时,这是无效的,因此使用BGW会使您的代码效率大大降低,因为您需要使用完全阻塞IO方法(或阻塞异步方法)。使用完全非BGW的解决方案可以避免完全阻塞线程。简而言之,这个特定的用例不适合BGW设计用于的模型;尝试强制它是…不推荐的。谢谢你澄清了这一点,我肯定会研究它,但是看到这个程序是多么的微不足道,我不打算重做它来利用任务。我更喜欢从我部分理解的事情开始,即BGW。这只是我为自己设置的一个项目,目的是学习语言:)
UI thread running
Worker thread running
0123-1234-1234 (The value of Serial)
Worker completed
No errors
{"success": "true","action": "validate","error": "None"} (Returned from web API)
License validation was successful
Success
RunWorkerCompleted finished